home *** CD-ROM | disk | FTP | other *** search
/ C & C++ Multimedia Cyber Classroom / C and C++ Multimedia Cyber Classroom (Prentice Hall) (1998).iso / cpphtp2 / cpphtp2.jar / chpt_23.gml < prev    next >
Text File  |  1998-03-03  |  95KB  |  2,312 lines

  1. <html>
  2. <chapter>
  3. <section type=Popup name=Terminology title="Terminology">
  4. <page>
  5. <font size=14>
  6. A<br>
  7. a+ file open mode 
  8. <a href="%s4p8"><img src=iicons/bullbib.gif></a>
  9. <br>
  10. B<br>
  11. binary digits 
  12. <a href="%s2p0"><img src=iicons/bullbib.gif></a>
  13. <br>
  14. bit 
  15. <a href="%s2p0"><img src=iicons/bullbib.gif></a>
  16. <br>
  17. byte 
  18. <a href="%s2p2"><img src=iicons/bullbib.gif></a>
  19. <a href="%s2p2"><img src=iicons/bullbib.gif></a>
  20. <a href="%s2p2"><img src=iicons/bullbib.gif></a>
  21. <br>
  22. C<br>
  23. character set 
  24. <a href="%s2p2"><img src=iicons/bullbib.gif></a>
  25. <br>
  26. characters 
  27. <a href="%s2p1"><img src=iicons/bullbib.gif></a>
  28. <a href="%s2p1"><img src=iicons/bullbib.gif></a>
  29. <br>
  30. D<br>
  31. data hierarchy 
  32. <a href="%s2p3"><img src=iicons/bullbib.gif></a>
  33. <a href="^Illustration::c:s0p1"><img src=iicons/bullbib.gif></a>
  34. <br>
  35. database 
  36. <a href="%s2p7"><img src=iicons/bullbib.gif></a>
  37. <br>
  38. database management 
  39. system (DBMS) 
  40. <a href="%s2p7"><img src=iicons/bullbib.gif></a>
  41. <br>
  42. </font>
  43.  
  44. </page>
  45. <page>
  46. <font size=14>
  47. decimal digits 
  48. <a href="%s2p1"><img src=iicons/bullbib.gif></a>
  49. <br>
  50. E<br>
  51. end-of-file indicator 
  52. <a href="%s4p4"><img src=iicons/bullbib.gif></a>
  53.  
  54. <a href="%s4p5"><img src=iicons/bullbib.gif></a>
  55. <br>
  56. F<br>
  57. feof 
  58. <a href="%s4p4"><img src=iicons/bullbib.gif></a>
  59. <a href="%s9p1"><img src=iicons/bullbib.gif></a>
  60. <br>
  61. fgetc 
  62. <a href="%s3p2"><img src=iicons/bullbib.gif></a>
  63. <br>
  64. field 
  65. <a href="%s2p2"><img src=iicons/bullbib.gif></a>
  66. <br>
  67. file 
  68. <a href="%s1p0"><img src=iicons/bullbib.gif></a>
  69. <a href="%s2p4"><img src=iicons/bullbib.gif></a>
  70. <br>
  71. file open mode 
  72. <a href="%s4p3"><img src=iicons/bullbib.gif></a>
  73. <br>
  74. file pointer 
  75. <a href="%s3p1"><img src=iicons/bullbib.gif></a>
  76. <br>
  77. file position pointer 
  78. <a href="%s5p3"><img src=iicons/bullbib.gif></a>
  79.  
  80. <a href="^Illustration::c:s0p8"><img src=iicons/bullbib.gif></a>
  81. <br>
  82. FILE structures 
  83. <a href="^Illustration::c:s0p4"><img src=iicons/bullbib.gif></a>
  84. <br>
  85. </font>
  86.  
  87. </page>
  88. <page>
  89. <font size=14>
  90. fopen 
  91. <a href="%s4p2"><img src=iicons/bullbib.gif></a>
  92. <a href="%s4p3"><img src=iicons/bullbib.gif></a>
  93. <br>
  94. fputc 
  95. <a href="%s3p2"><img src=iicons/bullbib.gif></a>
  96. <br>
  97. fread 
  98. <a href="%s7p0"><img src=iicons/bullbib.gif></a>
  99. <a href="%s9p0"><img src=iicons/bullbib.gif></a>
  100. <br>
  101. fseek 
  102. <a href="%s8p0"><img src=iicons/bullbib.gif></a>
  103. <br>
  104. fwrite 
  105. <a href="%s7p0"><img src=iicons/bullbib.gif></a>
  106. <a href="%s8p0"><img src=iicons/bullbib.gif></a>
  107. <br>
  108. O<br>
  109. open a file 
  110. <a href="%s3p0"><img src=iicons/bullbib.gif></a>
  111. <br>
  112. R<br>
  113. r+ open file mode 
  114. <a href="%s4p8"><img src=iicons/bullbib.gif></a>
  115. <br>
  116. randomly accessed file 
  117.  
  118. <a href="%s6p0"><img src=iicons/bullbib.gif></a>
  119. <a href="%s7p0"><img src=iicons/bullbib.gif></a>
  120. <br>
  121. record 
  122. <a href="%s2p3"><img src=iicons/bullbib.gif></a>
  123. <a href="%s4p0"><img src=iicons/bullbib.gif></a>
  124. <br>
  125. record key 
  126. <a href="%s2p5"><img src=iicons/bullbib.gif></a>
  127. <br>
  128. S<br>
  129. </font>
  130.  
  131. </page>
  132. <page>
  133. <font size=14>
  134. SEEK_CUR 
  135. <a href="%s8p3"><img src=iicons/bullbib.gif></a>
  136. <br>
  137. SEEK_END 
  138. <a href="%s8p3"><img src=iicons/bullbib.gif></a>
  139. <br>
  140. SEEK_SET 
  141. <a href="%s8p1"><img src=iicons/bullbib.gif></a>
  142. <a href="%s8p1"><img src=iicons/bullbib.gif></a>
  143. <br>
  144. sequential access file 
  145. <a href="%s4p0"><img src=iicons/bullbib.gif></a>
  146. <br>
  147. sizeof operator 
  148. <a href="%s7p5"><img src=iicons/bullbib.gif></a>
  149. <a href="%s7p5"><img src=iicons/bullbib.gif></a>
  150. <a href="^Exercises::c:s0p14"><img src=iicons/bullbib.gif></a>
  151. <br>
  152. standard error 
  153. <a href="%s3p0"><img src=iicons/bullbib.gif></a>
  154. <br>
  155. standard input 
  156. <a href="%s3p0"><img src=iicons/bullbib.gif></a>
  157. <br>
  158. standard output 
  159. <a href="%s3p0"><img src=iicons/bullbib.gif></a>
  160. <br>
  161. W<br>
  162. w+ file open mode 
  163. <a href="%s4p8"><img src=iicons/bullbib.gif></a>
  164. <br>
  165. <br>
  166. </font>
  167.  
  168. </page>
  169. </section>
  170. <section type=Popup name=Portable title="Portability">
  171. <page>
  172. The FILE structure is 
  173. operating system 
  174. dependent (i.e., the 
  175. members of the 
  176. structure vary among 
  177. systems based on how 
  178. each system handles its 
  179. files). <br>
  180.  
  181. </page>
  182. </section>
  183. <section type=Popup name=Quotes title="Quotes">
  184. <page>
  185. <i>I read part of it all the 
  186. way through. 
  187. </i><br>
  188. Samuel Goldwyn<br>
  189.  
  190. </page>
  191. <page>
  192. <i>Hats off! 
  193. </i><br>
  194. <i>The flag is passing by. 
  195. </i><br>
  196. Henry Holcomb Bennett<br>
  197.  
  198. </page>
  199. <page>
  200. <i>Consciousness ... does not 
  201. appear to itself chopped 
  202. up in bits. ... A "river" or 
  203. a "stream" are the 
  204. metaphors by which it is 
  205. most naturally described. 
  206. </i><br>
  207. William James<br>
  208.  
  209. </page>
  210. <page>
  211. <i>I can only assume that a 
  212. "Do Not File" document 
  213. is filed in a "Do Not File" 
  214. file. 
  215. </i><br>
  216. Senator Frank Church<p>
  217. Senate Intelligence 
  218. Subcommittee Hearing, 
  219. 1975<br>
  220.  
  221. </page>
  222. </section>
  223. <section type=Popup name=Illustration title="Illustrations">
  224. <page>
  225. <a href="^Illustration::c:s0p1">Fig. 23.1</a> - The data hierarchy.<br>
  226. <a href="^Illustration::c:s0p2">Fig. 23.2</a> - C's view of a file of n bytes.<br>
  227. <a href="^Code::c:s0p0">Fig. 23.3</a> - Creating a sequential file.<br>
  228. <a href="^Illustration::c:s0p3">Fig. 23.4</a> - End-of-file key combinations for various popular computer systems.<br>
  229. <a href="^Illustration::c:s0p4">Fig. 23.5</a> - The relationship between <b>FILE</b> pointers, <b>FILE</b> structures and FCBs.<br>
  230. <a href="^Illustration::c:s0p6">Fig. 23.6</a> - File open modes.<br>
  231. <a href="^Code::c:s0p1">Fig. 23.7</a> - Reading and printing a sequential file.<br>
  232. <a href="^Code::c:s0p2">Fig. 23.8</a> - Credit inquiry program.<br>
  233. <a href="^Illustration::c:s0p7">Fig. 23.10</a> - View of a randomly accessed file with fixed-length records.<br>
  234. <a href="^Code::c:s0p3">Fig. 23.11</a> - Creating a random access file sequentially.<br>
  235. <a href="^Code::c:s0p4">Fig. 23.12</a> - Writing data randomly to a randomly accessed file.<br>
  236. <a href="^Illustration::c:s0p8">Fig. 23.14</a> - The file position pointer indicating an offset of 5 bytes from the beginning of the 
  237. file.<br>
  238. <a href="^Code::c:s0p5">Fig. 23.15</a> - Reading a random access file sequentially.<br>
  239. <a href="^Code::c:s0p6">Fig. 23.16</a> - Bank account program.<br>
  240. <br>
  241.  
  242. </page>
  243. <page>
  244. <font size=18>Figure 23.1 - The data hierarchy.<img src="graphics/ch23/fig23001.gif" ></font><br>
  245.  
  246. </page>
  247. <page>
  248. <font size=18>Figure 23.2 - C's view of a file of n bytes.<img src="graphics/ch23/fig23002.gif" ></font><br>
  249.  
  250. </page>
  251. <page>
  252. <font size=18>Figure 23.4 - End-of-file key combinations for various popular computer systems.</font><br>
  253. <img src="graphics/ch23/fig23004.gif" ><br>
  254.  
  255. </page>
  256. <page>
  257. <font size=18>Figure 23.5 - The relationship between <b>FILE</b> pointers, <b>FILE</b> structures and FCBs 
  258. (Part 1 of 2).</font><br>
  259. <img src="graphics/ch23/fig23005a.gif" ><br>
  260.  
  261. </page>
  262. <page>
  263. <font size=18>Figure 23.5 - The relationship between<b> FILE</b> pointers,<b> FILE</b> structures and FCBs 
  264. (Part 2 of 2).</font><br>
  265. <img src="graphics/ch23/fig23005b.gif" ><br>
  266.  
  267. </page>
  268. <page>
  269. <font size=18>Figure 23.6 - File open modes.<img src="graphics/ch23/fig23006.gif" ></font><br>
  270.  
  271. </page>
  272. <page>
  273. <font size=18>Figure 23.10 - View of a randomly accessed file with fixed-length records.<img src="graphics/ch23/fig23010.gif" ></font><br>
  274.  
  275. </page>
  276. <page>
  277. <font size=18>Figure 23.14 - The file position pointer indicating an offset of 5 bytes from the 
  278. beginning of the file.<img src="graphics/ch23/fig23014.gif" ></font><br>
  279.  
  280. </page>
  281. </section>
  282. <section type=Popup name=Code title="Code Examples">
  283. <page>
  284. <font size=18>Figure 23.3 - Creating a sequential file. </font><br>
  285. <applet code=gsl.win.helper.TextBox width=580 height=300>
  286. <param  name="file" value="code/ch23/fig23_03.txt">
  287. </applet><br>
  288. <br>
  289. <foreign  name="copy2disk" url="!jcpy Source/fig23_03.jar">
  290. <foreign  name="audio" url="~audio/Ch23/23fig003.au">
  291. <foreign  name="execute" url="!jarexe Run/fig23_03.jar">
  292. <br>
  293.  
  294. </page>
  295. <page>
  296. <font size=18>Figure 23.7 - Reading and printing a sequential file.</font><br>
  297. <applet code=gsl.win.helper.TextBox width=580 height=300>
  298. <param  name="file" value="code/ch23/fig23_07.txt">
  299. </applet><br>
  300. <br>
  301. <foreign  name="copy2disk" url="!jcpy Source/fig23_07.jar">
  302. <foreign  name="audio" url="~audio/Ch23/23fig007.au">
  303. <foreign  name="execute" url="!jarexe Run/fig23_07.jar">
  304. <font size=2><br></font><font size=11><pre>
  305. <p>
  306. </pre></font>
  307.  
  308. </page>
  309. <page>
  310. <font size=18>Figure 23.8 - Credit inquiry program.</font><br>
  311. <applet code=gsl.win.helper.TextBox width=580 height=300>
  312. <param  name="file" value="code/ch23/fig23_08.txt">
  313. </applet><br>
  314. <br>
  315. <foreign  name="copy2disk" url="!jcpy Source/fig23_08.jar">
  316. <foreign  name="audio" url="~audio/Ch23/23fig008.au">
  317. <foreign  name="execute" url="!jarexe Run/fig23_08.jar">
  318. <br>
  319.  
  320. </page>
  321. <page>
  322. <font size=18>Figure 23.11 - Creating a random access file sequentially.</font><br>
  323. <applet code=gsl.win.helper.TextBox width=580 height=300>
  324. <param  name="file" value="code/ch23/fig23_11.txt">
  325. </applet><br>
  326. <br>
  327. <foreign  name="copy2disk" url="!jcpy Source/fig23_11.jar">
  328. <foreign  name="audio" url="~audio/Ch23/23fig011.au">
  329. <foreign  name="execute" url="!jarexe Run/fig23_11.jar">
  330. <br>
  331.  
  332. </page>
  333. <page>
  334. <font size=18>Figure 23.12 - Writing data randomly to a randomly accessed file.</font><br>
  335. <applet code=gsl.win.helper.TextBox width=580 height=300>
  336. <param  name="file" value="code/ch23/fig23_12.txt">
  337. </applet><br>
  338. <br>
  339. <foreign  name="copy2disk" url="!jcpy Source/fig23_12.jar">
  340. <foreign  name="audio" url="~audio/Ch23/23fig012.au">
  341. <foreign  name="execute" url="!jarexe Run/fig23_12.jar">
  342. <br>
  343.  
  344. </page>
  345. <page>
  346. <font size=18>Figure 23.15 - Reading a random access file sequentially.</font><br>
  347. <applet code=gsl.win.helper.TextBox width=580 height=300>
  348. <param  name="file" value="code/ch23/fig23_15.txt">
  349. </applet><br>
  350. <br>
  351. <foreign  name="copy2disk" url="!jcpy Source/fig23_15.jar">
  352. <foreign  name="audio" url="~audio/Ch23/23fig015.au">
  353. <foreign  name="execute" url="!jarexe Run/fig23_15.jar">
  354. <br>
  355.  
  356. </page>
  357. <page>
  358. <font size=18>Figure 23.16 - Bank account program.</font><br>
  359. <applet code=gsl.win.helper.TextBox width=580 height=300>
  360. <param  name="file" value="code/ch23/fig23_16.txt">
  361. </applet><br>
  362. <br>
  363. <foreign  name="copy2disk" url="!jcpy Source/fig23_16.jar">
  364. <foreign  name="audio" url="~audio/Ch23/23fig016.au">
  365. <foreign  name="execute" url="!jarexe Run/fig23_16.jar">
  366. <br>
  367.  
  368. </page>
  369. </section>
  370. <section type=Popup name=Practice title="Good Practices">
  371. <page>
  372. Be sure that calls to file 
  373. processing functions in 
  374. a program contain the 
  375. correct file pointers.<br>
  376.  
  377. </page>
  378. <page>
  379. Explicitly close each 
  380. file as soon as it is 
  381. known that the program 
  382. will not reference the 
  383. file again.<br>
  384.  
  385. </page>
  386. <page>
  387. Open a file only for 
  388. reading (and not 
  389. update) if the contents 
  390. of the file should not be 
  391. modified. This prevents 
  392. unintentional 
  393. modification of the 
  394. file's contents. This is 
  395. another example of the <br>
  396.  
  397. </page>
  398. <page>
  399. principle of least 
  400. privilege.<br>
  401.  
  402. </page>
  403. </section>
  404. <section type=Popup name=Perform title="Performance">
  405. <page>
  406. Closing a file can free 
  407. resources for which 
  408. other users or programs 
  409. may be waiting.<br>
  410.  
  411. </page>
  412. <page>
  413. Many programmers 
  414. mistakenly think <b>sizeof</b> 
  415. is a function, and that 
  416. using it generates the 
  417. execution-time 
  418. overhead of a function 
  419. call. There is no such 
  420. overhead because 
  421. <b>sizeof</b> is a compile-time 
  422. operator.<br>
  423.  
  424. </page>
  425. </section>
  426. <section type=Popup name=Answers title="Answers">
  427. <page pagename="Answers 23.1">
  428. <b>Answers 23.1</b><br>
  429. a) 1s, 0s.  b) Bit.  c) File.  d) Characters.  e) Database.  f) <b>fclose</b>.  g) <b>fscanf</b>.  <p>
  430. h) <b>getc</b> or <b>fgetc</b>. i) <b>fgets</b>.  j) <b>fopen</b>.  k) <b>fread</b>.  l) <b>fseek</b>.<br>
  431. <foreign  name="exercises" url="^Exercises::c:s0p0">
  432.  
  433. </page>
  434. <page pagename="Answers 23.2">
  435. <b>Answers 23.2</b><br>
  436. a)<spacer width=20 height=1>False. Function <b>fscanf</b> can be used to read from the standard input by including 
  437. the pointer to the standard input stream, <b>stdin</b>, in the call to <b>fscanf</b>.<br>
  438. b)<spacer width=20 height=1>False. These three streams are opened automatically by C when program 
  439. execution begins.<br>
  440. c)<spacer width=20 height=1>False. The files will be closed when program execution terminates, but all files 
  441. should be explicitly closed with <b>fclose</b>.<br>
  442. d)<spacer width=20 height=1>False. Function <b>rewind</b> can be used to reposition the file position pointer to the 
  443. beginning of the file.<br>
  444. e)<spacer width=20 height=1>True.<br>
  445. <foreign  name="exercises" url="^Exercises::c:s0p2">
  446.  
  447. </page>
  448. <page pagename="Answers 23.2">
  449. f)<spacer width=20 height=1>False. In most cases, sequential file records are not of uniform length. 
  450. Therefore, it is possible that updating a record will cause other data to be 
  451. overwritten.<br>
  452. g)<spacer width=20 height=1>True.<br>
  453. h)<spacer width=20 height=1>False. Records in a random access file are normally of uniform length.<br>
  454. i)<spacer width=20 height=1>False. It is possible to seek from the beginning of the file, from the end of the 
  455. file, and from the current location in the file according to the file position pointer.<br>
  456. <foreign  name="exercises" url="^Exercises::c:s0p2">
  457.  
  458. </page>
  459. <page pagename="Answers 23.3">
  460. <b>Answers 23.3</b><br>
  461. a)<spacer width=20 height=1><b>ofPtr = fopen("oldmast.dat", "r");
  462. </b><br>
  463. b)<spacer width=20 height=1><b>tfPtr = fopen("trans.dat", "r");
  464. </b><br>
  465. c)<spacer width=20 height=1><b>nfPtr = fopen("newmast.dat", "w");
  466. </b><br>
  467. d)<spacer width=20 height=1><b>fscanf(ofPtr,</b> <b>"%d%s%f", &accountNum, name, ¤tBalance);
  468. </b><br>
  469. e)<spacer width=20 height=1><b>fscanf(tfPtr, "%d%f", &accountNum, &dollarAmount);
  470. </b><br>
  471. f)<spacer width=20 height=1><b>fprintf(nfPtr,</b> <b>"%d</b> <b>%s</b> <b>%.2f", accountNum, name, currentBalance);
  472. </b><br>
  473. <foreign  name="exercises" url="^Exercises::c:s0p4">
  474.  
  475. </page>
  476. <page pagename="Answers 23.4">
  477. <b>Answers 23.4</b><br>
  478. a)<spacer width=20 height=1>Error: The file <b>"payables.dat"</b> has not been opened before the reference to its<p>
  479. file pointer.<br>
  480. <spacer width=20 height=1>Correction: Use <b>fopen</b> to open <b>"payables.dat"</b> for writing, appending, or 
  481. updating.<br>
  482. b)<spacer width=20 height=1>Error: The function <b>open</b> is not an ANSI C function.<br>
  483. <spacer width=20 height=1>Correction: Use function <b>fopen</b>.<br>
  484. c)<spacer width=20 height=1>Error: The <b>fscanf</b> statement uses the incorrect file pointer to refer to file 
  485. <b>"payables.dat"</b>. <br>
  486. <spacer width=20 height=1>Correction: Use file pointer <b>payPtr</b> to refer to <b>"payables.dat"</b>.<br>
  487. <foreign  name="exercises" url="^Exercises::c:s0p6">
  488.  
  489. </page>
  490. <page pagename="Answers 23.4">
  491. d)<spacer width=20 height=1>Error: The contents of the file are discarded because the file is opened for 
  492. writing (<b>"w"</b>).<br>
  493. <spacer width=20 height=1>Correction: To add data to the file, either open the file for updating (<b>"r+"</b>) or 
  494. open the file for appending (<b>"a"</b>).<br>
  495. e)<spacer width=20 height=1>Error: File <b>"courses.dat"</b> is opened for updating in <b>"w+"</b> mode which discards 
  496. the current contents of the file.<br>
  497. <spacer width=20 height=1>Correction: Open the file <b>"a" </b>mode.<br>
  498. <foreign  name="exercises" url="^Exercises::c:s0p6">
  499.  
  500. </page>
  501. <page pagename="Answers 23.5">
  502. <b>Answers 23.5</b><br>
  503. <font size=14><pre>
  504. /* Exercise 23.5 Solution */<p>
  505. /* NOTE: This program was run using the */<p>
  506. /* data in Exercise 23.8  */<p>
  507. #include <stdio.h><p>
  508. #include <stdlib.h><p>
  509. <p>
  510. main()<p>
  511. {<p>
  512.    int masterAccount, transactionAccount;<p>
  513.    float masterBalance, transactionBalance;<p>
  514.    char masterName[23];<p>
  515. </pre></font>
  516. <foreign  name="exercises" url="^Exercises::c:s0p8">
  517.  
  518. </page>
  519. <page pagename="Answers 23.5">
  520. <font size=14><pre>
  521.   FILE *ofPtr, *tfPtr, *nfPtr;<p>
  522. </pre></font>
  523. <font size=14><pre>
  524.    <p>
  525.    if ((ofPtr = fopen("oldmast.dat", "r")) == NULL) {<p>
  526.       printf("Unable to open oldmast.dat\n");<p>
  527.       exit(1);<p>
  528.    }<p>
  529.    <p>
  530.    if ((tfPtr = fopen("trans.dat", "r")) == NULL) {<p>
  531.       printf("Unable to open trans.dat\n");<p>
  532.       exit(1);<p>
  533.    }<p>
  534.    if ((nfPtr = fopen("newmast.dat", "w")) == NULL) {<p>
  535. </pre></font>
  536. <foreign  name="exercises" url="^Exercises::c:s0p8">
  537.  
  538. </page>
  539. <page pagename="Answers 23.5">
  540. <font size=14><pre>
  541.       printf("Unable to open newmast.dat\n");<p>
  542. </pre></font>
  543. <font size=14><pre>
  544.       exit(1);<p>
  545.    }<p>
  546. <p>
  547.    printf("Processing....\n");<p>
  548.    fscanf(tfPtr, "%d%f", &transactionAccount, &transactionBalance);<p>
  549. <p>
  550.    while (!feof(tfPtr)) {<p>
  551.       fscanf(ofPtr, "%d%s%f", &masterAccount, masterName, &masterBalance);<p>
  552. <p>
  553. </pre></font>
  554. <foreign  name="exercises" url="^Exercises::c:s0p8">
  555.  
  556. </page>
  557. <page pagename="Answers 23.5">
  558. <font size=14><pre>
  559.       while (masterAccount < transactionAccount && 
  560. !feof(ofPtr)) {<p>
  561. </pre></font>
  562. <font size=14><pre>
  563.          fprintf(nfPtr, "%d %s %.2f\n", masterAccount, masterName,<p>
  564. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>masterBalance);<p>
  565.          printf("%d %s %.2f\n", masterAccount, masterName, masterBalance);<p>
  566.          fscanf(ofPtr, "%d%s%f", &masterAccount, masterName,<p>
  567. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>  <spacer width=20 height=1><spacer width=20 height=1>&masterBalance);<p>
  568.       }<p>
  569.          <p>
  570.       if (masterAccount == transactionAccount) {<p>
  571. </pre></font>
  572. <foreign  name="exercises" url="^Exercises::c:s0p8">
  573.  
  574. </page>
  575. <page pagename="Answers 23.5">
  576. <font size=14><pre>
  577.          masterBalance += transactionBalance;         <p>
  578. </pre></font>
  579. <font size=14><pre>
  580.          fprintf(nfPtr, "%d %s %.2f\n", masterAccount, masterName,<p>
  581. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>masterBalance);<p>
  582.          printf("%d %s %.2f\n", masterAccount, masterName, masterBalance);<p>
  583.       }<p>
  584.       else if (masterAccount > transactionAccount) {<p>
  585.          printf("Unmatched transaction record for account %d\n", <p>
  586.                 transactionAccount);<p>
  587. </pre></font>
  588. <foreign  name="exercises" url="^Exercises::c:s0p8">
  589.  
  590. </page>
  591. <page pagename="Answers 23.5">
  592. <font size=14><pre>
  593.          fprintf(nfPtr, "%d %s %.2f\n", masterAccount, 
  594. masterName,<p>
  595. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>masterBalance);<p>
  596. </pre></font>
  597. <font size=14><pre>
  598.          printf("%d %s %.2f\n", masterAccount, masterName, masterBalance);<p>
  599.       }<p>
  600.       else<p>
  601.          printf("Unmatched transaction record for account %d\n", <p>
  602.                 transactionAccount);<p>
  603.         <p>
  604.       fscanf(tfPtr, "%d%f", &transactionAccount, &transactionBalance);<p>
  605. </pre></font>
  606. <foreign  name="exercises" url="^Exercises::c:s0p8">
  607.  
  608. </page>
  609. <page pagename="Answers 23.5">
  610. <font size=14><pre>
  611.    }<p>
  612. </pre></font>
  613. <font size=14><pre>
  614.    <p>
  615.    while (!feof(ofPtr)) {<p>
  616.       fscanf(ofPtr, "%d%s%f", &masterAccount, masterName, &masterBalance);<p>
  617.       fprintf(nfPtr, "%d %s %.2f", masterAccount, masterName,<p>
  618. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>masterBalance);<p>
  619.       printf("%d %s %.2f", masterAccount, masterName, masterBalance);<p>
  620.    }<p>
  621.    <p>
  622.    fclose(ofPtr);<p>
  623. </pre></font>
  624. <foreign  name="exercises" url="^Exercises::c:s0p8">
  625.  
  626. </page>
  627. <page pagename="Answers 23.5">
  628. <font size=14><pre>
  629.    fclose(tfPtr);<p>
  630. </pre></font>
  631. <font size=14><pre>
  632.    fclose(nfPtr);<p>
  633. <p>
  634.    return 0;<p>
  635. }<p>
  636. <p>
  637. <spacer width=20 height=1>Processing....<p>
  638. <spacer width=20 height=1>100 Jones 375.31<p>
  639. <spacer width=20 height=1>300 Smith 89.30<p>
  640. <spacer width=20 height=1>Unmatched transaction record for account 400<p>
  641. <spacer width=20 height=1>500 Sharp 0.00<p>
  642. <spacer width=20 height=1>700 Green -14.22<p>
  643. <spacer width=20 height=1>Unmatched transaction record for account 900<p>
  644. </pre></font>
  645. <foreign  name="exercises" url="^Exercises::c:s0p8">
  646.  
  647. </page>
  648. <page pagename="Answers 23.6">
  649. <b>Answers 23.6</b><br>
  650. <font size=14><pre>
  651. /* Exercise 23.6 Solution */<p>
  652. #include <stdio.h><p>
  653. #include <string.h><p>
  654. #include <ctype.h><p>
  655. #include <stdlib.h><p>
  656. <p>
  657. void initializeFile(FILE *);<p>
  658. void inputData(FILE *);<p>
  659. int instructions(void);<p>
  660. void listTools(FILE *);<p>
  661. void updateRecord(FILE *);<p>
  662. </pre></font>
  663. <foreign  name="exercises" url="^Exercises::c:s0p12">
  664.  
  665. </page>
  666. <page pagename="Answers 23.6">
  667. <font size=14><pre>
  668. void insertRecord(FILE *);<p>
  669. </pre></font>
  670. <font size=14><pre>
  671. void deleteRecord(FILE *);<p>
  672. <p>
  673. struct hardwareData {<p>
  674.    int partNumber;<p>
  675.    char toolName[30];<p>
  676.   int inStock;<p>
  677.    float unitPrice;<p>
  678. };<p>
  679. <p>
  680. main()<p>
  681. {<p>
  682.    FILE *filePtr;<p>
  683.    char response[2];<p>
  684. </pre></font>
  685. <foreign  name="exercises" url="^Exercises::c:s0p12">
  686.  
  687. </page>
  688. <page pagename="Answers 23.6">
  689. <font size=14><pre>
  690.    int process;<p>
  691. </pre></font>
  692. <font size=14><pre>
  693. <p>
  694.    printf("Should the file be initialized (Y or N): ");<p>
  695.    scanf("%s", response);<p>
  696.       <p>
  697.    while (toupper(response[0]) != 'Y' && toupper(response[0]) != 'N') {<p>
  698.       printf("Invalid response. Enter Y or N: ");<p>
  699.       scanf("%s", response);<p>
  700.    }<p>
  701.       <p>
  702.    if (toupper(response[0]) == 'Y') {<p>
  703. </pre></font>
  704. <foreign  name="exercises" url="^Exercises::c:s0p12">
  705.  
  706. </page>
  707. <page pagename="Answers 23.6">
  708. <font size=14><pre>
  709.       if ((filePtr = fopen("hardware.dat", "w")) == NULL) {<p>
  710. </pre></font>
  711. <font size=14><pre>
  712.          printf("File could not be opened.\n");<p>
  713.          exit(1);<p>
  714.       }<p>
  715.          <p>
  716.       initializeFile(filePtr);<p>
  717.       inputData(filePtr);<p>
  718.       fclose(filePtr);<p>
  719.    }<p>
  720.             <p>
  721.    if ((filePtr = fopen("hardware.dat", "r+")) == NULL) {<p>
  722.       printf("File could not be opened.\n");<p>
  723. </pre></font>
  724. <foreign  name="exercises" url="^Exercises::c:s0p12">
  725.  
  726. </page>
  727. <page pagename="Answers 23.6">
  728. <font size=14><pre>
  729.       exit(1);<p>
  730. </pre></font>
  731. <font size=14><pre>
  732.    }<p>
  733.    while ((process = instructions()) != 5) {<p>
  734.       switch (process) {<p>
  735.          case 1:<p>
  736.             listTools(filePtr);<p>
  737.             break;<p>
  738.          case 2:<p>
  739.             updateRecord(filePtr);<p>
  740.             break;<p>
  741.          case 3:<p>
  742.             insertRecord(filePtr);<p>
  743. </pre></font>
  744. <foreign  name="exercises" url="^Exercises::c:s0p12">
  745.  
  746. </page>
  747. <page pagename="Answers 23.6">
  748. <font size=14><pre>
  749.             break;            <p>
  750. </pre></font>
  751. <font size=14><pre>
  752.          case 4:<p>
  753.             deleteRecord(filePtr);<p>
  754.             break;            <p>
  755.       }<p>
  756.    }<p>
  757.    <p>
  758.    fclose(filePtr);<p>
  759.    return 0;<p>
  760. }<p>
  761. <p>
  762. void initializeFile(FILE *fPtr)<p>
  763. </pre></font>
  764. <foreign  name="exercises" url="^Exercises::c:s0p12">
  765.  
  766. </page>
  767. <page pagename="Answers 23.6">
  768. <font size=14><pre>
  769. {<p>
  770. </pre></font>
  771. <font size=14><pre>
  772.    struct hardwareData blankItem = {0, "", 0, 0.0};<p>
  773.    int i;<p>
  774.    <p>
  775.    for (i = 0; i <= 99; i++) <p>
  776.       fwrite(&blankItem, sizeof(struct hardwareData), 1, fPtr);<p>
  777. }<p>
  778. <p>
  779. void inputData(FILE *fPtr)<p>
  780. {<p>
  781.    struct hardwareData temp;<p>
  782. </pre></font>
  783. <foreign  name="exercises" url="^Exercises::c:s0p12">
  784.  
  785. </page>
  786. <page pagename="Answers 23.6">
  787. <font size=14><pre>
  788.    char c;<p>
  789. </pre></font>
  790. <font size=14><pre>
  791.    <p>
  792.    printf("Enter the partnumber (0 - 99, -1 to end input): ");<p>
  793.    scanf("%d", &temp.partNumber);<p>
  794.    <p>
  795.    while (temp.partNumber != -1) {<p>
  796.       printf("Enter the tool name, quantity, and price:\n");<p>
  797.       scanf(" %[^0-9] %d%f", temp.toolName, &temp.inStock,<p>
  798. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>&temp.unitPrice);<p>
  799.       fseek(fPtr, temp.partNumber * sizeof(struct hardwareData),<p>
  800. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>SEEK_SET);<p>
  801. </pre></font>
  802. <foreign  name="exercises" url="^Exercises::c:s0p12">
  803.  
  804. </page>
  805. <page pagename="Answers 23.6">
  806. <font size=14><pre>
  807.       fwrite(&temp, sizeof(struct hardwareData), 1, fPtr);<p>
  808. </pre></font>
  809. <font size=14><pre>
  810. <p>
  811.       printf("Enter the partnumber (0 - 99, -1 to end input): ");<p>
  812.       scanf("%d", &temp.partNumber);<p>
  813.    }<p>
  814. }<p>
  815. <p>
  816. int instructions(void) <p>
  817. {<p>
  818.    int choice;<p>
  819.    printf("\n%s\n%s\n%s\n%s\n%s\n%s\n? ", "Enter a choice:", <p>
  820. </pre></font>
  821. <foreign  name="exercises" url="^Exercises::c:s0p12">
  822.  
  823. </page>
  824. <page pagename="Answers 23.6">
  825. <font size=14><pre>
  826.           "1  List all tools.", "2  Update record.", "3  Insert 
  827. record.",<p>
  828. </pre></font>
  829. <font size=14><pre>
  830.           "4  Delete record.", "5  End program.");<p>
  831.    scanf("%d", &choice);<p>
  832.    <p>
  833.    while (choice < 1 || choice > 5) {<p>
  834.       printf("Invalid choice. Enter again: ");<p>
  835.       scanf("%d", &choice);<p>
  836.    }<p>
  837.    <p>
  838.    return choice;<p>
  839. }<p>
  840. </pre></font>
  841. <foreign  name="exercises" url="^Exercises::c:s0p12">
  842.  
  843. </page>
  844. <page pagename="Answers 23.6">
  845. <font size=14><pre>
  846. void listTools(FILE *fPtr)<p>
  847. </pre></font>
  848. <font size=14><pre>
  849. {<p>
  850.    struct hardwareData temp;<p>
  851. <p>
  852.    fseek(fPtr, sizeof(struct hardwareData), SEEK_SET);<p>
  853.    printf("%8s  %-29s%10s%8s\n", "Record #", "Tool name", "Quantity",<p>
  854. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>"Cost");<p>
  855.           <p>
  856.    while (!feof(fPtr)) {<p>
  857.       fread(&temp, sizeof(struct hardwareData), 1, fPtr);<p>
  858. <p>
  859.       if (temp.partNumber)<p>
  860. </pre></font>
  861. <foreign  name="exercises" url="^Exercises::c:s0p12">
  862.  
  863. </page>
  864. <page pagename="Answers 23.6">
  865. <font size=14><pre>
  866.          printf("%-8d  %-29s%10d%8.2f\n", temp.partNumber,<p>
  867. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>temp.toolName, temp.inStock, temp.unitPrice);<p>
  868. </pre></font>
  869. <font size=14><pre>
  870.    }<p>
  871. }<p>
  872. <p>
  873. <p>
  874. void updateRecord(FILE *fPtr)<p>
  875. {<p>
  876.    struct hardwareData temp;<p>
  877.    int part;<p>
  878.    <p>
  879.    printf("Enter the partnumber for update: ");<p>
  880. </pre></font>
  881. <foreign  name="exercises" url="^Exercises::c:s0p12">
  882.  
  883. </page>
  884. <page pagename="Answers 23.6">
  885. <font size=14><pre>
  886.    scanf("%d", &part);<p>
  887. </pre></font>
  888. <font size=14><pre>
  889.    fseek(fPtr, part * sizeof(struct hardwareData), SEEK_SET);<p>
  890.    fread(&temp, sizeof(struct hardwareData), 1, fPtr);<p>
  891.    <p>
  892.    if (temp.partNumber) {<p>
  893.       printf("%8s  %-29s%10s%8s\n", "Record #", "Tool name", "Quantity","Cost");<p>
  894.       printf("%-8d  %-29s%10d%8.2f\n", temp.partNumber, temp.toolName, <p>
  895.              temp.inStock, temp.unitPrice);<p>
  896.       printf("Enter the tool name, quantity, and price:\n");<p>
  897.       scanf(" %[^0-9] %d%f", temp.toolName, &temp.inStock,<p>
  898. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>Price);<p>
  899. </pre></font>
  900. <foreign  name="exercises" url="^Exercises::c:s0p12">
  901.  
  902. </page>
  903. <page pagename="Answers 23.6">
  904. <font size=14><pre>
  905.       fseek(fPtr, temp.partNumber * sizeof(struct 
  906. hardwareData),<p>
  907. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>SEEK_SET);<p>
  908. </pre></font>
  909. <font size=14><pre>
  910.       fwrite(&temp, sizeof(struct hardwareData), 1, fPtr);<p>
  911.    }<p>
  912.    else<p>
  913.       printf("Cannot update. The record is empty.\n");<p>
  914. }<p>
  915. <p>
  916. <p>
  917. void insertRecord(FILE *fPtr)<p>
  918. {<p>
  919. </pre></font>
  920. <foreign  name="exercises" url="^Exercises::c:s0p12">
  921.  
  922. </page>
  923. <page pagename="Answers 23.6">
  924. <font size=14><pre>
  925.    struct hardwareData temp;<p>
  926. </pre></font>
  927. <font size=14><pre>
  928.    int part;<p>
  929.    printf("Enter the partnumber for insertion: ");<p>
  930.    scanf("%d", &part);<p>
  931.    fseek(fPtr, part * sizeof(struct hardwareData), SEEK_SET);<p>
  932.    fread(&temp, sizeof(struct hardwareData), 1, fPtr);<p>
  933.    <p>
  934.    if (!temp.partNumber) {<p>
  935.       temp.partNumber = part;<p>
  936.       printf("Enter the tool name, quantity, and price:\n");<p>
  937.       scanf(" %[^0-9] %d%f", temp.toolName, &temp.inStock,<p>
  938. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>Price);<p>
  939. </pre></font>
  940. <foreign  name="exercises" url="^Exercises::c:s0p12">
  941.  
  942. </page>
  943. <page pagename="Answers 23.6">
  944. <font size=14><pre>
  945.       fseek(fPtr, temp.partNumber * sizeof(struct 
  946. hardwareData),<p>
  947. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>SEEK_SET);<p>
  948. </pre></font>
  949. <font size=14><pre>
  950.       fwrite(&temp, sizeof(struct hardwareData), 1, fPtr);<p>
  951.    }<p>
  952.    else<p>
  953.       printf("Cannot insert. The record contains information.\n");<p>
  954. }<p>
  955. void deleteRecord(FILE *fPtr)<p>
  956. {<p>
  957.    struct hardwareData blankItem = {0, "", 0, 0.0}, temp;<p>
  958. </pre></font>
  959. <foreign  name="exercises" url="^Exercises::c:s0p12">
  960.  
  961. </page>
  962. <page pagename="Answers 23.6">
  963. <font size=14><pre>
  964.    int part;<p>
  965. </pre></font>
  966. <font size=14><pre>
  967.    <p>
  968.    printf("Enter the partnumber for deletion: ");<p>
  969.    scanf("%d", &part);<p>
  970.    fseek(fPtr, part * sizeof(struct hardwareData), SEEK_SET);<p>
  971.    fread(&temp, sizeof(struct hardwareData), 1, fPtr);<p>
  972.    <p>
  973.    if (temp.partNumber) {<p>
  974.       fseek(fPtr, part * sizeof(struct hardwareData), SEEK_SET);<p>
  975.       fwrite(&blankItem, sizeof(struct hardwareData), 1, fPtr);<p>
  976. </pre></font>
  977. <foreign  name="exercises" url="^Exercises::c:s0p12">
  978.  
  979. </page>
  980. <page pagename="Answers 23.6">
  981. <font size=14><pre>
  982.       printf("Record deleted.\n");<p>
  983. </pre></font>
  984. <font size=14><pre>
  985.    }<p>
  986.    else<p>
  987.       printf("Cannot delete. The record is empty.\n");<p>
  988. }<p>
  989. </pre></font>
  990. <foreign  name="exercises" url="^Exercises::c:s0p12">
  991.  
  992. </page>
  993. <page pagename="Answers 23.7">
  994. <b>Answers 23.7</b><br>
  995. <font size=14><pre>
  996. /* Exercise 23.7 Solution */<p>
  997. #include <stdio.h><p>
  998. <p>
  999. main()<p>
  1000. {<p>
  1001.    FILE *outPtr;<p>
  1002.    <p>
  1003.    outPtr = fopen("datasize.dat", "w");<p>
  1004.    <p>
  1005.    fprintf(outPtr, "%s%16s\n", "Data type", "Size");<p>
  1006.    fprintf(outPtr, "%s%21d\n", "char", sizeof(char));<p>
  1007. </pre></font>
  1008. <foreign  name="exercises" url="^Exercises::c:s0p14">
  1009.  
  1010. </page>
  1011. <page pagename="Answers 23.7">
  1012. <font size=14><pre>
  1013.    fprintf(outPtr, "%s%12d\n", "unsigned char", 
  1014. sizeof(unsigned char));<p>
  1015. </pre></font>
  1016. <font size=14><pre>
  1017.    fprintf(outPtr, "%s%16d\n", "short int", sizeof(short int));<p>
  1018.    fprintf(outPtr, "%s%7d\n", "unsigned short int",<p>
  1019. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>sizeof(unsigned short int));<p>
  1020.    fprintf(outPtr, "%s%22d\n", "int", sizeof(int));<p>
  1021.    fprintf(outPtr, "%s%13d\n", "unsigned int", sizeof(unsigned int));<p>
  1022.    fprintf(outPtr, "%s%17d\n", "long int", sizeof(long int));<p>
  1023.    fprintf(outPtr, "%s%8d\n", "unsigned long int",<p>
  1024. <spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1><spacer width=20 height=1>sizeof(unsigned long int));<p>
  1025. </pre></font>
  1026. <foreign  name="exercises" url="^Exercises::c:s0p14">
  1027.  
  1028. </page>
  1029. <page pagename="Answers 23.7">
  1030. <font size=14><pre>
  1031.    fprintf(outPtr, "%s%20d\n", "float", sizeof(float));<p>
  1032. </pre></font>
  1033. <font size=14><pre>
  1034.    fprintf(outPtr, "%s%19d\n", "double", sizeof(double));<p>
  1035.    fprintf(outPtr, "%s%14d\n", "long double", sizeof(long double));<p>
  1036.    <p>
  1037.    fclose(outPtr);<p>
  1038.    return 0;<p>
  1039. }<p>
  1040. </pre></font>
  1041. <foreign  name="exercises" url="^Exercises::c:s0p14">
  1042.  
  1043. </page>
  1044. <page pagename="Answers 23.7">
  1045. <font size=14><pre>
  1046. <spacer width=20 height=1>Data type            Size<p>
  1047. </pre></font>
  1048. <font size=14><pre>
  1049. <spacer width=20 height=1>char                    1<p>
  1050. <spacer width=20 height=1>unsigned char           1<p>
  1051. <spacer width=20 height=1>short int               2<p>
  1052. <spacer width=20 height=1>unsigned short int      2<p>
  1053. <spacer width=20 height=1>int                     2<p>
  1054. <spacer width=20 height=1>unsigned int            2<p>
  1055. <spacer width=20 height=1>long int                4<p>
  1056. <spacer width=20 height=1>unsigned long int       4<p>
  1057. <spacer width=20 height=1>float                   4<p>
  1058. <spacer width=20 height=1>double                 10<p>
  1059. <spacer width=20 height=1>long double            10<p>
  1060. </pre></font>
  1061. <foreign  name="exercises" url="^Exercises::c:s0p14">
  1062.  
  1063. </page>
  1064. </section>
  1065. <section type=Popup name=Exercises title="Exercises">
  1066. <page pagename="Exercise 23.1">
  1067. <b>Exercise 23.1</b><br>
  1068. <spacer width=20 height=1>Fill in the blanks in each of the following:<br>
  1069. a)<spacer width=20 height=1>Ultimately, all data items processed by a computer are reduced to 
  1070. combinations of <tt><b>________</b></tt> and <tt><b>________</b></tt>.<br>
  1071. b)<spacer width=20 height=1>The smallest data item a computer can process is called a <tt><b>________</b></tt>.<br>
  1072. c)<spacer width=20 height=1>A <tt><b>________</b></tt> is a group of related records.<br>
  1073. d)<spacer width=20 height=1>Digits, letters, and special symbols are referred to as <tt><b>________</b></tt>.<br>
  1074. e)<spacer width=20 height=1>A group of related files is called a <tt><b>________</b></tt>.<br>
  1075. f)<spacer width=20 height=1>The <tt><b>________</b></tt> function closes a file.<br>
  1076. g)<spacer width=20 height=1>The <tt><b>________</b></tt> statement reads data from a file in a manner similar to how <b>scanf</b> 
  1077. reads from <b>stdin</b>.<br>
  1078. h)<spacer width=20 height=1>The <tt><b>________</b></tt> function reads a character from a specified file.ButtonName<br>
  1079. <foreign  name="answers" url="^Answers::c:s0p0">
  1080.  
  1081. </page>
  1082. <page pagename="Exercise 23.1">
  1083. i)<spacer width=20 height=1>The <tt><b>________</b></tt> function reads a line from a specified file.<br>
  1084. j)<spacer width=20 height=1>The <tt><b>________</b></tt> function opens a file.<br>
  1085. k)<spacer width=20 height=1>The <tt><b>________</b></tt> function is normally used when reading data from a file in random 
  1086. access applications.<br>
  1087. l)<spacer width=20 height=1>The ________ function repositions the file position pointer to a specific 
  1088. location in the file.<br>
  1089. <foreign  name="answers" url="^Answers::c:s0p0">
  1090.  
  1091. </page>
  1092. <page pagename="Exercise 23.2">
  1093. <b>Exercise 23.2</b><br>
  1094. <spacer width=20 height=1>State which of the following are true and which are false (for those that are false, 
  1095. explain why):<br>
  1096. a)<spacer width=20 height=1>Function <b>fscanf</b> cannot be used to read data from the standard input.<br>
  1097. b)<spacer width=20 height=1>The programmer must explicitly use <b>fopen</b> to open the standard input, 
  1098. standard output, and standard error streams.<br>
  1099. c)<spacer width=20 height=1>A program must explicitly call function <b>fclose</b> to close a file.<br>
  1100. d)<spacer width=20 height=1>If the file position pointer points to a location in a sequential file other than the 
  1101. beginning of the file, the file must be closed and reopened to read from the 
  1102. beginning of the file.<br>
  1103. e)<spacer width=20 height=1>Function <b>fprintf</b> can write to the standard output.<br>
  1104. <foreign  name="answers" url="^Answers::c:s0p1">
  1105.  
  1106. </page>
  1107. <page pagename="Exercise 23.2">
  1108. f)<spacer width=20 height=1>Data in sequential access files is always updated without overwriting other 
  1109. data.<br>
  1110. g)<spacer width=20 height=1>It is not necessary to search through all the records in a randomly accessed file 
  1111. to find a specific record.<br>
  1112. h)<spacer width=20 height=1>Records in randomly accessed files are not of uniform length.<br>
  1113. i)<spacer width=20 height=1>Function <b>fseek</b> may only seek relative to the beginning of a file.<br>
  1114. <foreign  name="answers" url="^Answers::c:s0p1">
  1115.  
  1116. </page>
  1117. <page pagename="Exercise 23.3">
  1118. <b>Exercise 23.3</b><br>
  1119. Write a single statement to accomplish each of the following. Assume that each 
  1120. of these statements applies to the same program.<br>
  1121. a)<spacer width=20 height=1>Write a statement that opens file <b>"oldmast.dat"</b> for reading and assigns the 
  1122. returned file pointer to <b>ofPtr</b>.<br>
  1123. b)<spacer width=20 height=1>Write a statement that opens file <b>"trans.dat"</b> for reading and assigns the 
  1124. returned file pointer to <b>tfPtr</b>.<br>
  1125. c)<spacer width=20 height=1>Write a statement that opens file <b>"newmast.dat"</b> for writing (and creation) 
  1126. and assigns the returned file pointer to <b>nfPtr</b>.<br>
  1127. d)<spacer width=20 height=1>Write a statement that reads a record from the file <b>"oldmast.dat"</b>. The record 
  1128. consists of integer <b>accountNum</b>, string <b>name</b>, and floating point 
  1129. <b>currentBalance</b>.<br>
  1130. <foreign  name="answers" url="^Answers::c:s0p3">
  1131.  
  1132. </page>
  1133. <page pagename="Exercise 23.3">
  1134. e)<spacer width=20 height=1>Write a statement that reads a record from the file <b>"trans.dat"</b>. The record 
  1135. consists of integer <b>accountNum</b> and floating point <b>dollarAmount</b>.<br>
  1136. f)<spacer width=20 height=1>Write a statement that writes a record to the file <b>"newmast.dat"</b>. The record 
  1137. consists of integer <b>accountNum</b>, string <b>name</b>, and floating point 
  1138. <b>currentBalance</b>.<br>
  1139. <foreign  name="answers" url="^Answers::c:s0p3">
  1140.  
  1141. </page>
  1142. <page pagename="Exercise 23.4">
  1143. <b>Exercise 23.4</b><br>
  1144. <spacer width=20 height=1>Find the error in each of the following program segments. Explain how the error 
  1145. can be corrected.<br>
  1146. a)<spacer width=20 height=1>The file referred to by <b>fPtr</b> (<b>"payables.dat"</b>) has not been opened.<br>
  1147. <b><spacer width=20 height=1>fprintf(fPtr, "%d%s%d\n", account, company, amount);
  1148. </b><br>
  1149. b)<spacer width=20 height=1><b>open("receive.dat", "r+");
  1150. </b><br>
  1151. c)<spacer width=20 height=1>The following statement should read a record from the file <b>"payables.dat"</b>. 
  1152. File pointer <b>payPtr</b> refers to this file, and file pointer <b>recPtr</b> refers to the file 
  1153. <b>"receive.dat"</b>.<br>
  1154. <b><spacer width=20 height=1>fscanf(recPtr, "%d%s%d\n", &account, company, &amount);
  1155. </b><br>
  1156. <foreign  name="answers" url="^Answers::c:s0p4">
  1157. <br>
  1158. <br>
  1159.  
  1160. </page>
  1161. <page pagename="Exercise 23.4">
  1162. d)<spacer width=20 height=1>The file <b>"tools.dat"</b> should be opened to add data to the file without 
  1163. discarding the current data.<br>
  1164. <font size=2><br></font><font size=11><pre>
  1165. <spacer width=20 height=1>if ((tfPtr = fopen("tools.dat", "w")) != NULL)<p>
  1166. </pre></font>
  1167. e)<spacer width=20 height=1>The file <b>"courses.dat"</b> should be opened for appending without modifying the 
  1168. current contents of the file.<br>
  1169. <b><spacer width=20 height=1>if ((cfPtr = fopen("courses.dat", "w+")) != NULL)
  1170. </b><br>
  1171. <foreign  name="answers" url="^Answers::c:s0p4">
  1172.  
  1173. </page>
  1174. <page pagename="Exercise 23.5">
  1175. <b>Exercise 23.5</b><br>
  1176. Exercise 11.3 asked the reader to write a series of single statements. Actually, 
  1177. these statements form the core of an important type of file processing program, 
  1178. namely, a file-matching program. In commercial data processing, it is common 
  1179. to have several files in each system. In an accounts receivable system, for 
  1180. example, there is generally a master file containing detailed information about 
  1181. each customer such as the customer's name, address, telephone number, 
  1182. outstanding balance, credit limit, discount terms, contract arrangements, and 
  1183. possibly a condensed history of recent purchases and cash payments.<br>
  1184. As transactions occur (i.e., sales are made and cash payments arrive in the mail), 
  1185. they are entered into a file. At the end of each business period (i.e., a month for<br>
  1186. <foreign  name="answers" url="^Answers::c:s0p6">
  1187.  
  1188. </page>
  1189. <page pagename="Exercise 23.5">
  1190. some companies, a week for others, and a day in some cases) the file of 
  1191. transactions (called <b>"trans.dat"</b> in Exercise 11.3 is applied to the master file 
  1192. (called <b>"oldmast.dat"</b> in Exercise 11.3), thus updating each account's record of 
  1193. purchases and payments. After each of these updating runs, the master file is 
  1194. rewritten as a new file (<b>"newmast.dat"</b>), which is then used at the end of the 
  1195. next business period to begin the updating process again.<br>
  1196. File-matching programs must deal with certain problems that do not exist in 
  1197. single-file programs. For example, a match does not always occur. A customer 
  1198. on the master file may not have made any purchases or cash payments in the 
  1199. current business period, and therefore no record for this customer will appear on 
  1200. the transaction file. Similarly, a customer who did make some purchases or cash<br>
  1201. <foreign  name="answers" url="^Answers::c:s0p6">
  1202.  
  1203. </page>
  1204. <page pagename="Exercise 23.5">
  1205. payments may have just moved to this community, and the company may not 
  1206. have had a chance to create a master record for this customer.<br>
  1207. Use the statements written in Exercise 11.3 as a basis for writing a complete file-
  1208. matching accounts receivable program. Use the account number on each file as 
  1209. the record key for matching purposes. Assume that each file is a sequential file 
  1210. with records stored in increasing account number order.<br>
  1211. When a match occurs (i.e., records with the same account number appear on 
  1212. both the master file and the transaction file), add the dollar amount on the 
  1213. transaction file to the current balance on the master file, and write the 
  1214. <b>"newmast.dat"</b> record. (Assume that purchases are indicated by positive 
  1215. amounts on the transaction file, and that payments are indicated by negative 
  1216. amounts.) When there is a master record for a particular account but no<br>
  1217. <foreign  name="answers" url="^Answers::c:s0p6">
  1218.  
  1219. </page>
  1220. <page pagename="Exercise 23.5">
  1221. corresponding transaction record, merely write the master record to 
  1222. <b>"newmast.dat"</b>. When there is a transaction record but no corresponding 
  1223. master record, print the message <b>"Unmatched transaction record for account 
  1224. number ..."</b> (fill in the account number from the transaction record).<br>
  1225. <foreign  name="answers" url="^Answers::c:s0p6">
  1226.  
  1227. </page>
  1228. <page pagename="Exercise 23.6">
  1229. <b>Exercise 23.6</b><br>
  1230. You are the owner of a hardware store and need to keep an inventory that can tell 
  1231. you what tools you have, how many you have, and the cost of each one. Write a 
  1232. program that initializes the file <b>"hardware.dat"</b> to 100 empty records, lets you 
  1233. input the data concerning each tool, enables you to list all your tools, lets you 
  1234. delete a record for a tool that you no longer have, and lets you update <i>any</i> 
  1235. information in the file. The tool identification number should be the record 
  1236. number. Use the following information to start your file:<br>
  1237. <foreign  name="answers" url="^Answers::c:s0p14">
  1238.  
  1239. </page>
  1240. <page pagename="Exercise 23.6">
  1241. <img src="graphics/ch23/ex23006.gif" ><br>
  1242. <foreign  name="answers" url="^Answers::c:s0p14">
  1243.  
  1244. </page>
  1245. <page pagename="Exercise 23.7">
  1246. <b>Exercise 23.7</b><br>
  1247. Write a program that uses the <b>sizeof</b> operator to determine the sizes in bytes of 
  1248. the various data types on your computer system. Write the results to the file 
  1249. <b>"datasize.dat"</b> so you may print the results later. The format for the results in 
  1250. the file should be as shown on the next screen.<br>
  1251. <br>
  1252. Note: The type sizes on your computer may not be the same as the ones listed in 
  1253. the table.<br>
  1254. <foreign  name="answers" url="^Answers::c:s0p32">
  1255.  
  1256. </page>
  1257. <page pagename="Exercise 23.7">
  1258. <img src="graphics/ch23/ex23007.gif" ><br>
  1259. <foreign  name="answers" url="^Answers::c:s0p32">
  1260.  
  1261. </page>
  1262. </section>
  1263. <section type=Popup name=Objective title="Objectives">
  1264. <page>
  1265. <indent width=8 delay>*   To be able to create, read, write, and update files.</indent>
  1266. <indent width=8 delay>*   To become familiar with sequential access file processing.</indent>
  1267. <indent width=8 delay>*   To become familiar with random access file processing.</indent>
  1268. <foreign  name="audio" url="~audio/Ch23/23obj.au">
  1269. <br>
  1270.  
  1271. </page>
  1272. </section>
  1273. <section type=Popup name=Errors title="Common Errors">
  1274. <page>
  1275. Opening an existing file 
  1276. for writing (<b>"w"</b>) 
  1277. when, in fact, the user 
  1278. wants to preserve the 
  1279. file; the contents of the 
  1280. file are discarded 
  1281. without warning. <br>
  1282.  
  1283. </page>
  1284. <page>
  1285. Forgetting to open a file 
  1286. before attempting to 
  1287. reference it in a 
  1288. program.<br>
  1289.  
  1290. </page>
  1291. <page>
  1292. Using the wrong file 
  1293. pointer to refer to a file.<br>
  1294.  
  1295. </page>
  1296. <page>
  1297. Opening a nonexistent 
  1298. file for reading.<br>
  1299.  
  1300. </page>
  1301. <page>
  1302. Opening a file for 
  1303. reading or writing 
  1304. without having been 
  1305. granted the appropriate 
  1306. access rights to the file 
  1307. (this is operating-
  1308. system dependent).<br>
  1309.  
  1310. </page>
  1311. <page>
  1312. Opening a file for 
  1313. writing when no disk 
  1314. space is available. 
  1315. <a href="^Illustration::c:s0p6">Figure 23.6</a> lists the file 
  1316. open modes.<br>
  1317.  
  1318. </page>
  1319. <page>
  1320. Opening a file with the 
  1321. incorrect file mode can 
  1322. lead to devastating 
  1323. errors. For example, 
  1324. opening a file in write 
  1325. mode (<b>"w"</b>) when it 
  1326. should be opened in 
  1327. update mode (<b>"r+"</b>) 
  1328. causes the contents of 
  1329. the file to be discarded.<br>
  1330.  
  1331. </page>
  1332. </section>
  1333. <section type=Body name=Default title="23 File Processing">
  1334. <page>
  1335. <font size=18 bold>23 File Processing</font><hr>
  1336. <a href="#s1p0">23.1<spacer width=20 height=1>Introduction</a> <br>
  1337. <a href="#s2p0">23.2<spacer width=20 height=1>The Data Hierarchy</a> <br>
  1338. <a href="#s3p0">23.3<spacer width=20 height=1>Files and Streams</a> <br>
  1339. <a href="#s4p0">23.4<spacer width=20 height=1>Creating a Sequential Access File</a> <br>
  1340. <a href="#s5p0">23.5<spacer width=20 height=1>Reading Data from a Sequential Access File</a> <br>
  1341. <a href="#s6p0">23.6<spacer width=20 height=1>Random Access Files</a> <br>
  1342. <a href="#s7p0">23.7<spacer width=20 height=1>Creating a Randomly Accessed File</a> <br>
  1343. <a href="#s8p0">23.8<spacer width=20 height=1>Writing Data Randomly to a Randomly Accessed 
  1344. File</a> <br>
  1345. <foreign  name="objectivesButton" url="^Objective::c:s0p0">
  1346. <foreign  name="quotes" url="^Quotes::c:s0p0">
  1347.  
  1348. </page>
  1349. <page>
  1350. <a href="#s9p0">23.9<spacer width=20 height=1>Reading Data Randomly from a Randomly 
  1351. Accessed File</a> <br>
  1352. <a href="#s10p0">23.10<spacer width=20 height=1>Case Study: A Transaction Processing Program</a> <br>
  1353. <a href="#s11p0">23.11<spacer width=20 height=1>Summary</a> <br>
  1354. <a href="^Terminology::c:s0p0">Terminology</a>  <br>
  1355. <a href="^Illustration::c:s0p0">Figures</a>  <br>
  1356. <foreign  name="objectivesButton" url="^Objective::c:s0p0">
  1357. <foreign  name="quotes" url="^Quotes::c:s0p0">
  1358.  
  1359. </page>
  1360. </section>
  1361. <section type=Body name=Default title="23.1 Introduction">
  1362. <page>
  1363. <font size=18 bold>23.1 Introduction</font><hr>
  1364. Storage of data in variables and arrays is temporary; all 
  1365. such data is lost when a program terminates. Files  are 
  1366. used for permanent retention of large amounts of data. 
  1367. Computers store files on secondary storage devices, 
  1368. especially disk storage devices. In this chapter, we 
  1369. explain how data files are created, updated, and 
  1370. processed by C programs. We consider both sequential 
  1371. access files and random access files.<br>
  1372. <spacer width=16 height=1><br>
  1373.  
  1374. </page>
  1375. </section>
  1376. <section type=Body name=Default title="23.2 The Data Hierarchy">
  1377. <page>
  1378. <font size=18 bold>23.2 The Data Hierarchy</font><hr>
  1379. Ultimately, all data items processed by a computer are 
  1380. reduced to combinations of zeros and ones. This occurs 
  1381. because it is simple and economical to build electronic 
  1382. devices that can assume two stable states--one of the 
  1383. states represents <b>0</b> and the other represents <b>1</b>. It is 
  1384. remarkable that the impressive functions performed by 
  1385. computers involve only the most fundamental 
  1386. manipulations of <b>0</b>s and <b>1</b>s.<br>
  1387. <spacer width=16 height=1>The smallest data item in a computer can assume the 
  1388. value <b>0</b> or the value <b>1</b>. Such a data item is called a <i>bit</i>  
  1389. (short for "<i>b</i>inary dig<i>it</i>"--a digit that can assume one of <br>
  1390.  
  1391. </page>
  1392. <page>
  1393. two values). Computer circuitry performs various 
  1394. simple bit manipulations such as determining the value 
  1395. of a bit, setting the value of a bit, and reversing a bit 
  1396. (from <b>1</b> to <b>0</b> or from <b>0</b> to <b>1</b>).<br>
  1397. <spacer width=16 height=1>It is cumbersome for programmers to work with data in 
  1398. the low-level form of bits. Instead, programmers prefer 
  1399. to work with data in the form of <i>decimal digits</i> (i.e., 0, 
  1400. 1, 2, 3, 4, 5, 6, 7, 8, and 9), <i>letters</i> (i.e., A through Z, 
  1401. and a through z), and <i>special symbols</i> (i.e., $, @, %, &, 
  1402. *, (, ), -, +, ", :, ?, /, and many others). Digits, letters, 
  1403. and special symbols are referred to as <i>characters</i>. The 
  1404. set of all characters that may be used to write programs 
  1405. and represent data items on a particular computer is <br>
  1406.  
  1407. </page>
  1408. <page>
  1409. called that computer's <i>character set</i>. Since computers 
  1410. can process only <b>1</b>s and <b>0</b>s, every character in a 
  1411. computer's character set is represented as a pattern of 
  1412. <b>1</b>s and <b>0</b>s (called a <i>byte</i>). Today, bytes are most 
  1413. commonly composed of eight bits. Programmers create 
  1414. programs and data items as characters; computers then 
  1415. manipulate and process these characters as patterns of 
  1416. bits.<br>
  1417. <spacer width=16 height=1>Just as characters are composed of bits, <i>fields</i>  are 
  1418. composed of characters. A field is a group of characters 
  1419. that conveys meaning. For example, a field consisting 
  1420. solely of uppercase and lowercase letters can be used to 
  1421. represent a person's name.<br>
  1422.  
  1423. </page>
  1424. <page>
  1425. Data items processed by computers form a <i>data 
  1426. hierarchy</i>  in which data items become larger and more 
  1427. complex in structure as we progress from bits, to 
  1428. characters (bytes), to fields, and so on.<br>
  1429. <spacer width=16 height=1>A <i>record</i> (i.e., a <b>struct</b> in C) is composed of several 
  1430. fields. In a payroll system, for example, a record for a 
  1431. particular employee might consist of the following 
  1432. fields:<br>
  1433. 1. Social Security number <br>
  1434. 2. Name<br>
  1435. 3. Address <br>
  1436. 4. Hourly salary rate <br>
  1437. 5. Number of exemptions claimed<br>
  1438.  
  1439. </page>
  1440. <page>
  1441. 6. Year-to-date earnings <br>
  1442. 7. Amount of Federal taxes withheld, etc.<br>
  1443. Thus, a record is a group of related fields. In the 
  1444. preceding example, each of the fields belongs to the 
  1445. same employee. Of course, a particular company may 
  1446. have many employees, and will have a payroll record 
  1447. for each employee. A <i>file</i>  is a group of related records. 
  1448. A company's payroll file normally contains one record 
  1449. for each employee. Thus, a payroll file for a small 
  1450. company might contain only 22 records, whereas a 
  1451. payroll file for a large company might contain 100,000 
  1452. records. It is not unusual for an organization to have 
  1453. hundreds or even thousands of files, with many <br>
  1454.  
  1455. </page>
  1456. <page>
  1457. containing millions or even billions of characters of 
  1458. information. With the increasing popularity of laser 
  1459. optical disks and multimedia technology, even trillion-
  1460. byte files will soon be common. <b><a href="^Illustration::c:s0p1">Fig.<img src="bckgrnds/icons/ill_ico.gif" align=sidebar> 23.1</a></b> illustrates the 
  1461. data hierarchy.<br>
  1462. <spacer width=16 height=1>To facilitate the retrieval of specific records from a file, 
  1463. at least one field in each record is chosen as a <i>record 
  1464. key</i>. A record key identifies a record as belonging to a 
  1465. particular person or entity. For example, in the payroll 
  1466. record described in this section, the Social Security 
  1467. number would normally be chosen as the record key.<br>
  1468. <spacer width=16 height=1>There are many ways of organizing records in a file. 
  1469. The most popular type of organization is called a <br>
  1470.  
  1471. </page>
  1472. <page>
  1473. <i>sequential file</i>  in which records are typically stored in 
  1474. order by the record key field. In a payroll file, records 
  1475. are usually placed in order by Social Security number. 
  1476. The first employee record in the file contains the lowest 
  1477. Social Security number, and subsequent records contain 
  1478. increasingly higher Social Security numbers. <br>
  1479. <spacer width=16 height=1>Most businesses utilize many different files to store 
  1480. data. For example, companies may have payroll files, 
  1481. accounts receivable files (listing money due from 
  1482. clients), accounts payable files (listing money due to 
  1483. suppliers), inventory files (listing facts about all the 
  1484. items handled by the business), and many other types of 
  1485. files. A group of related files is sometimes called a <br>
  1486.  
  1487. </page>
  1488. <page>
  1489. <i>database</i>. A collection of programs designed to create 
  1490. and manage databases is called a <i>database management 
  1491. system</i> (DBMS).<br>
  1492.  
  1493. </page>
  1494. </section>
  1495. <section type=Body name=Default title="23.3 Files and Streams">
  1496. <page>
  1497. <font size=18 bold>23.3 Files and Streams</font><hr>
  1498. C views each file simply as a sequential stream of bytes 
  1499. (<a href="^Illustration::c:s0p2"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar><b>Fig. 23.2</b></a>). Each file ends either with an <i>end-of-file 
  1500. marker</i>  or at a specific byte number recorded in a 
  1501. system maintained, administrative data structure. When 
  1502. a file is <i>opened</i>, a stream is associated with the file. 
  1503. Three files and their associated streams are 
  1504. automatically opened when program execution 
  1505. begins--the <i>standard input</i>, the <i>standard output</i>, and 
  1506. the <i>standard error</i>. Streams provide communication 
  1507. channels between files and programs. For example, the 
  1508. standard input stream enables a program to read data <br>
  1509.  
  1510. </page>
  1511. <page>
  1512. from the keyboard, and the standard output stream 
  1513. enables a program to print data on the screen. Opening 
  1514. a file returns a pointer to a <b>FILE</b> structure (defined in 
  1515. <b><stdio.h></b>) that contains information used to process the 
  1516. file. This structure includes a <i>file descriptor</i>, i.e., an 
  1517. index into an operating system array called the <i>open file 
  1518. table</i>. Each array element contains a <i>file control block 
  1519. (FCB)</i> that the operating system uses to administer a 
  1520. particular file. The standard input, standard output, and 
  1521. standard error are manipulated using file pointers <b>stdin</b>, 
  1522. <b>stdout</b>, and <b>stderr</b>.<br>
  1523. <spacer width=16 height=1>The standard library provides many functions for 
  1524. reading data from files and for writing data to files. <br>
  1525.  
  1526. </page>
  1527. <page>
  1528. Function <b>fgetc</b>, like <b>getchar</b>, reads one character from a 
  1529. file. Function <b>fgetc</b> receives as an argument a <b>FILE</b> 
  1530. pointer for the file from which a character will be read. 
  1531. The call <b>fgetc(stdin)</b> reads one character from <b>stdin</b>--
  1532. the standard input. This call is equivalent to the call 
  1533. <b>getchar()</b>. Function <b>fputc</b>, like <b>putchar</b>, writes one 
  1534. character to a file. Function <b>fputc</b> receives as 
  1535. arguments a character to be written and a pointer for the 
  1536. file to which the character will be written. The function 
  1537. call <b>fputc('a',</b> <b>stdout)</b> writes the character <b>'a'</b> to 
  1538. <b>stdout</b>--the standard output. This call is equivalent to 
  1539. <b>putchar('a')</b>. <br>
  1540.  
  1541. </page>
  1542. <page>
  1543. Several other functions used to read data from standard 
  1544. input and write data to standard output have similarly 
  1545. named file processing functions. The <b>fgets</b> and <b>fputs</b> 
  1546. functions, for example, can be used to read a line from a 
  1547. file and write a line to a file, respectively. Their 
  1548. counterparts for reading from standard input and 
  1549. writing to standard output are <b>gets</b> and <b>puts</b>. In the next 
  1550. several sections, we introduce the file processing 
  1551. equivalents of functions <b>scanf</b> and <b>printf</b>--<b>fscanf</b> and 
  1552. <b>fprintf</b>. Later in the chapter we discuss functions <b>fread</b> 
  1553. and <b>fwrite</b>.<br>
  1554. <br>
  1555.  
  1556. </page>
  1557. </section>
  1558. <section type=Body name=Default title="23.4 Creating a Sequential Access File">
  1559. <page>
  1560. <font size=18 bold>23.4 Creating a Sequential Access File</font><hr>
  1561. C imposes no structure on a file. Thus, notions like a 
  1562. record of a file do not exist as part of the C language. 
  1563. Therefore, the programmer must provide any file 
  1564. structure to meet the requirements of each particular 
  1565. application. In the following example, we see how the 
  1566. programmer may impose a record structure on a file.<br>
  1567. <spacer width=16 height=1>The program of <a href="^Code::c:s0p0"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.3 </b></a>creates a simple sequential 
  1568. access file that might be used in an accounts receivable 
  1569. system to help keep track of the amounts owed by a 
  1570. company's credit clients. For each client, the program 
  1571. obtains an account number, the client's name, and the <br>
  1572.  
  1573. </page>
  1574. <page>
  1575. client's balance (i.e., the amount the client owes the 
  1576. company for goods and services received in the past). 
  1577. The data obtained for each client constitutes a "record" 
  1578. for that client. The account number is used as the record 
  1579. key in this application--the file will be created and 
  1580. maintained in account number order. This program 
  1581. assumes the user enters the records in account number 
  1582. order. In a comprehensive accounts receivable system, a 
  1583. sorting capability would be provided so the user could 
  1584. enter the records in any order. The records would then 
  1585. be sorted and written to the file. <br>
  1586. <spacer width=16 height=1>Now let us examine this program. The statement<br>
  1587. <font size=2><br></font><font size=11><pre>
  1588. FILE *cfPtr;<p>
  1589. </pre></font>
  1590.  
  1591. </page>
  1592. <page>
  1593. states that <b>cfptr</b> is a pointer to a <b>FILE</b> structure. The C 
  1594. program administers each file with a separate <b>FILE</b> 
  1595. structure. The programmer need not know the specifics 
  1596. of the <b>FILE</b> structure to use files. We will soon see 
  1597. precisely how the <b>FILE</b> structure leads indirectly to the 
  1598. operating system's file control block (FCB) for a file. <br>
  1599. <spacer width=16 height=1>Each open file must <a href="^Portable::c:s0p0"><img src="bckgrnds/icons/port_ico.gif" align=sidebar></a>have a separately declared pointer 
  1600. of type <b>FILE</b> that is used to refer to the file. The line<br>
  1601. <font size=2><br></font><font size=11><pre>
  1602. if ((cfPtr = fopen("clients.dat", "w")) == NULL)<p>
  1603. </pre></font>
  1604. names the file--<b>"clients.dat"</b>--to be used by the 
  1605. program and establishes a "line of communication" 
  1606. with the file. The file pointer <b>cfPtr</b> is assigned a pointer 
  1607. to the <b>FILE</b> structure for the file opened with <b>fopen</b>. <br>
  1608.  
  1609. </page>
  1610. <page>
  1611. Function <b>fopen</b> takes two arguments: a file name and a 
  1612. <i>file open mode</i>. The file open mode <b>"w"</b> indicates that 
  1613. the file is to be opened for <i>writing</i>. If a file does not 
  1614. exist and it is opened for writing, <b>fopen</b> creates the file. 
  1615. If an existing file is opened for writing, the contents of 
  1616. the file are discarded without warning. In the program, 
  1617. the <b>if</b>  <a href="^Errors::c:s0p0"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>structure is used to determine whether the file 
  1618. pointer <b>cfPtr</b> is <b>NULL</b> (i.e., the file is not opened). If it 
  1619. is <b>NULL</b>, an  <a href="^Errors::c:s0p1"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>error message is printed and the program 
  1620. ends. Otherwise, the input is processed and written to 
  1621. the file. <br>
  1622. <spacer width=16 height=1><b><spacer width=20 height=1></b>The program prompts the user to enter the various fields 
  1623. for each record, or to enter end-of-file when data entry <br>
  1624.  
  1625. </page>
  1626. <page>
  1627. is complete. <a href="^Illustration::c:s0p3"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar>Figure 23.4</a> lists the key combinations for 
  1628. entering end-of-file for various computer systems. <br>
  1629. <spacer width=16 height=1>The line <br>
  1630. <font size=2><br></font><font size=11><pre>
  1631. while (!feof(stdin))<p>
  1632. </pre></font>
  1633. uses function <b>feof</b> to determine whether the <i>end-of-file 
  1634. indicator</i> is set for the file to which <b>stdin</b> refers. The 
  1635. end-of-file indicator informs the program that there is 
  1636. no more data to be processed. In the program of <a href="^Code::c:s0p0">Fig.<img src="bckgrnds/icons/code_ico.gif" align=sidebar> 
  1637. 23.3</a>, the end-of-file indicator is set for the standard 
  1638. input when the user enters the end-of-file key 
  1639. combination. The argument to function <b>feof</b> is a pointer 
  1640. to the file being tested for the end-of-file indicator 
  1641. (<b>stdin</b> in this case). The function returns a nonzero <br>
  1642.  
  1643. </page>
  1644. <page>
  1645. value (true) once the end-of-file indicator has been set; 
  1646. otherwise, zero is returned. The <b>while</b> structure that 
  1647. includes the <b>feof</b> call in this program continues 
  1648. executing while the end-of-file indicator is not set. <br>
  1649. <spacer width=16 height=1><spacer width=20 height=1>The statement<br>
  1650. <font size=2><br></font><font size=11><pre>
  1651. fprintf(cfPtr, "%d %s %.2f\n", account,<p>
  1652.         name,balance);<p>
  1653. </pre></font>
  1654. writes  <a href="^Errors::c:s0p2"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>data to the file <b>clients.dat</b>. The data may be 
  1655. retrieved later by a program designed to read the file 
  1656. (see <a href="#s5p0">Section 23.5</a>). Function <b>fprintf</b> is  <a href="^Practice::c:s0p0"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>equivalent to 
  1657. <b>printf</b> except that <b>fprintf</b> also receives as an argument 
  1658. a file pointer for the file to which the data will be 
  1659. written. <br>
  1660.  
  1661. </page>
  1662. <page>
  1663. After the user enters end-of-file, the program closes the 
  1664. <b>clients.dat</b> file with <b>fclose</b> and terminates. Function 
  1665. <b>fclose</b> also receives the  <a href="^Practice::c:s0p1"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>file pointer (rather than the file 
  1666. name) as an argument. If function <b>fclose</b> is not called 
  1667. explicitly, the operating system normally will close the 
  1668. file when program execution terminates. This is an 
  1669. example of  <a href="^Perform::c:s0p0"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>operating system "housekeeping."<br>
  1670. <spacer width=16 height=1>In the sample execution for the program of <a href="^Code::c:s0p0"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.3</b></a>, the 
  1671. user enters information for five accounts, and then 
  1672. enters end-of-file to signal that data entry is complete. 
  1673. The sample execution does not show how the data 
  1674. records actually appear in the file. To verify that the file 
  1675. has been created successfully, in the next section we <br>
  1676.  
  1677. </page>
  1678. <page>
  1679. present a program that reads the file and prints its 
  1680. contents. <br>
  1681. <spacer width=16 height=1><a href="^Illustration::c:s0p4"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar><b>Figure 23.5</b></a> illustrates the relationship between <b>FILE</b> 
  1682. pointers, <b>FILE</b> structures, and FCBs in memory. When 
  1683. the file <b>"clients.dat"</b> is opened, an FCB for the file is 
  1684. copied into memory. The figure shows the connection 
  1685. between the file pointer returned by <b>fopen</b> and the FCB 
  1686. used by the operating system to administer the file.<br>
  1687. <spacer width=16 height=1>Programs may process no files, one file, or several files. 
  1688. Each file used in a program must have a unique name 
  1689. and will have a different file pointer returned by <b>fopen</b>. 
  1690. All subsequent file processing functions after the file is 
  1691. opened must refer to the file with the appropriate file <br>
  1692.  
  1693. </page>
  1694. <page>
  1695. pointer. Files may be opened in one of several modes. 
  1696. To <a href="^Errors::c:s0p3"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>create a file, or to discard the contents of a file 
  1697. before <a href="^Errors::c:s0p4"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>writing data, open the file for writing (<b>"w"</b>). To 
  1698. read an <a href="^Errors::c:s0p5"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>existing file, open it for reading (<b>"r"</b>). To add 
  1699. records to the end of an existing <a href="^Errors::c:s0p6"><img src="bckgrnds/icons/cpe_ico.gif" align=sidebar></a>file, open the file for 
  1700. appending (<b>"a"</b>). To open a file so that it may be 
  1701. written to and read from, open the file for updating in 
  1702. one of the three update modes--<b>"r+"</b>, <b>"w+"</b>, or <b>a+"</b>. 
  1703. Mode <b>"r+"</b> opens a file for reading and writing. Mode 
  1704. <b>"w+"</b> creates a file for reading and writing. If the file 
  1705. already exists, the file is opened and the current 
  1706. contents of the file are discarded. Mode <b>"a+"</b> opens a <br>
  1707.  
  1708. </page>
  1709. <page>
  1710. file for reading and writing--all writing is done at the 
  1711. end of the file. If the file does not exist, it is created. <br>
  1712. <spacer width=16 height=1>If an  <a href="^Practice::c:s0p2"><img src="bckgrnds/icons/gpp_ico.gif" align=sidebar></a>error occurs while opening a file in any mode, 
  1713. <b>fopen</b> returns <b>NULL</b>.<br>
  1714.  
  1715. </page>
  1716. </section>
  1717. <section type=Body name=Default title="23.5 Reading Data from a Sequential Access File">
  1718. <page>
  1719. <font size=18 bold>23.5 Reading Data from a Sequential Access 
  1720. File</font><hr>
  1721. Data are stored in files so that the data may be retrieved 
  1722. for processing when needed. The previous section 
  1723. demonstrated how to create a file for sequential access. 
  1724. In this section, we discuss how to read data sequentially 
  1725. from a file.<br>
  1726. <spacer width=16 height=1>The program of <a href="^Code::c:s0p1"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.7</b></a> reads records from the file 
  1727. <b>"clients.dat"</b> created by the program of <a href="^Code::c:s0p0"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.3</b></a>, and 
  1728. prints the contents of the records. The statement<br>
  1729. <font size=2><br></font><font size=11><pre>
  1730. FILE *cfPtr;<p>
  1731. </pre></font>
  1732. indicates that <b>cfPtr</b> is a pointer to a <b>FILE</b>. The line <br>
  1733.  
  1734. </page>
  1735. <page>
  1736. <font size=2><br></font><font size=11><pre>
  1737. if ((cfPtr = fopen("clients.dat", "r")) == NULL)<p>
  1738. </pre></font>
  1739. attempts to open the file <b>"clients.dat"</b> for reading 
  1740. (<b>"r"</b>), and determines whether the file is opened 
  1741. successfully (i.e., <b>fopen</b> does not return <b>NULL</b>). The 
  1742. statement<br>
  1743. <font size=2><br></font><font size=11><pre>
  1744. fscanf(cfPtr, "%d%s%f", &account, name, &balance);<p>
  1745. </pre></font>
  1746. reads a "record" from the file. Function <b>fscanf</b> is 
  1747. equivalent to function <b>scanf</b> except <b>fscanf</b> receives as 
  1748. an argument a file pointer for the file from which the 
  1749. data is read. After the preceding statement is executed 
  1750. the first time, <b>account</b> will have the value <b>100</b>, <b>name</b> 
  1751. will have the value <b>"Jones"</b>, and <b>balance</b> will have the <br>
  1752.  
  1753. </page>
  1754. <page>
  1755. value <b>24.98</b>. Each time the second <b>fscanf</b> statement is 
  1756. executed, another record is read from the file and 
  1757. <b>account</b>, <b>name</b>, and <b>balance</b> take on new values. When 
  1758. the end of the file is reached, the file is closed and the 
  1759. program terminates. <br>
  1760. <spacer width=16 height=1>To retrieve data sequentially from a file, a program 
  1761. normally starts reading from the beginning of the file, 
  1762. and reads all data consecutively until the desired data 
  1763. are found. It may be desirable to process the data 
  1764. sequentially in a file several times (from the beginning 
  1765. of the file) during the execution of a program. A 
  1766. statement such as<br>
  1767. <font size=2><br></font><font size=11><pre>
  1768. rewind(cfPtr);<p>
  1769. </pre></font>
  1770.  
  1771. </page>
  1772. <page>
  1773. causes a program's <i>file position pointer</i>--indicating the 
  1774. number of the next byte in the file to be read or 
  1775. written--to be repositioned to the beginning of the file 
  1776. (i.e., byte 0) pointed to by <b>cfPtr</b>. The file position 
  1777. pointer is not really a pointer. Rather it is an integer 
  1778. value that specifies the byte location in the file at which 
  1779. the next read or write is to occur. This is sometimes 
  1780. referred to as the <i>file offset</i>. The file position pointer is a 
  1781. member of the <b>FILE</b> structure associated with each file. <br>
  1782. <spacer width=16 height=1>We now present a program (<a href="^Code::c:s0p2"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.8</b></a>) that allows a credit 
  1783. manager to obtain lists of customers with zero balances 
  1784. (i.e., customers who do not owe any money), customers 
  1785. with credit balances (i.e., customers to whom the <br>
  1786.  
  1787. </page>
  1788. <page>
  1789. company owes money), and customers with debit 
  1790. balances (i.e., customers who owe the company money 
  1791. for goods and services received). A credit balance is a 
  1792. negative amount; a debit balance is a positive amount.<br>
  1793. <spacer width=16 height=1>The program displays a menu and allows the credit 
  1794. manager to enter one of three options to obtain credit 
  1795. information. Option 1 produces a list of accounts with 
  1796. zero balances. Option 2 produces a list of accounts with 
  1797. credit balances. Option 3 produces a list of accounts 
  1798. with debit balances. Option 4 terminates program 
  1799. execution. .<br>
  1800. <spacer width=16 height=1>Note that data in this type of sequential file cannot be 
  1801. modified without the risk of destroying other data in the <br>
  1802.  
  1803. </page>
  1804. <page>
  1805. file. For example, if the name "<b>White</b>" needed to be 
  1806. changed to "<b>Worthington</b>," the old name cannot 
  1807. simply be overwritten. The record for <b>White</b> was 
  1808. written to the file as<br>
  1809. <font size=2><br></font><font size=11><pre>
  1810. 300 White 0.00<p>
  1811. </pre></font>
  1812. If the record is rewritten beginning at the same location 
  1813. in the file using the new name, the record would be<p>
  1814. <br>
  1815. <font size=2><br></font><font size=11><pre>
  1816. 300 Worthington 0.00<p>
  1817. </pre></font>
  1818. The new record is larger than the original record. The 
  1819. characters beyond the second "<b>o</b>" in "<b>Worthington</b>" 
  1820. would overwrite the beginning of the next sequential <br>
  1821.  
  1822. </page>
  1823. <page>
  1824. record in the file. The problem here is that in the 
  1825. formatted input/output model using <b>fprintf</b> and <b>fscanf</b>, 
  1826. fields--and hence records--can vary in size. For 
  1827. example,  7, 14, -117, 2074, and 27383 are all <b>int</b>s 
  1828. stored in the same number of bytes internally, but they 
  1829. print on the screen or <b>fprintf</b> on the disk as different-
  1830. sized fields.<br>
  1831. <spacer width=16 height=1>Therefore, sequential access with <b>fprint</b> and <b>fscanf</b> is 
  1832. not usually used to update records in place. Instead, the 
  1833. entire file is usually rewritten. To make the preceding 
  1834. name change, the records before <b>300</b> <b>White</b> <b>0.00</b> in 
  1835. such a sequential access file would be copied to a new 
  1836. file, the new record would be written, and the records <br>
  1837.  
  1838. </page>
  1839. <page>
  1840. after <b>300</b> <b>White</b> <b>0.00</b> would be copied to the new file. 
  1841. This requires processing every record in the file to 
  1842. update one record. <br>
  1843.  
  1844. </page>
  1845. </section>
  1846. <section type=Body name=Default title="23.6 Random Access Files">
  1847. <page>
  1848. <font size=18 bold>23.6 Random Access Files</font><hr>
  1849. As we stated previously, records in a file created with 
  1850. the formatted output function <b>fprintf</b> are not 
  1851. necessarily the same length. However, individual 
  1852. records of a <i>randomly accessed file</i> are normally fixed 
  1853. in length and may be accessed directly (and thus 
  1854. quickly) without searching through other records. This 
  1855. makes randomly accessed files appropriate for airline 
  1856. reservation systems, banking systems, point-of-sale 
  1857. systems, and other kinds of <i>transaction processing 
  1858. systems</i> that require rapid access to specific data. There 
  1859. are other ways of implementing randomly accessed <br>
  1860.  
  1861. </page>
  1862. <page>
  1863. files, but we will limit our discussion to this straight 
  1864. forward approach using fixed-length records.<br>
  1865. <spacer width=16 height=1>Because every record in a randomly accessed file 
  1866. normally has the same length, the exact location of a 
  1867. record relative to the beginning of the file can be 
  1868. calculated as a function of the record key. We will soon 
  1869. see how this facilitates immediate access to specific 
  1870. records, even in large files. <br>
  1871. <spacer width=16 height=1><a href="^Illustration::c:s0p7">Figure<img src="bckgrnds/icons/ill_ico.gif" align=sidebar> 23.10</a> illustrates one way to implement a 
  1872. randomly accessed file. Such a file is like a freight train 
  1873. with many cars--some empty and some with cargo. 
  1874. Each car in the train is the same length.<br>
  1875.  
  1876. </page>
  1877. <page>
  1878. Data can be inserted in a randomly accessed file 
  1879. without destroying other data in the file. Data stored 
  1880. previously can also be updated or deleted without 
  1881. rewriting the entire file. In the following sections we 
  1882. explain how to create a randomly accessed file, enter 
  1883. data, read the data both sequentially and randomly, 
  1884. update the data, and delete data no longer needed.<br>
  1885.  
  1886. </page>
  1887. </section>
  1888. <section type=Body name=Default title="23.7 Creating a Randomly Accessed File">
  1889. <page>
  1890. <font size=18 bold>23.7 Creating a Randomly Accessed File</font><hr>
  1891. Function <b>fwrite</b> transfers a specified number of bytes 
  1892. beginning at a specified location in memory to a file. 
  1893. The data is written beginning at the location in the file 
  1894. indicated by the file position pointer. Function <b>fread</b> 
  1895. transfers a specified number of bytes from the location 
  1896. in the file specified by the file position pointer to an 
  1897. area in memory beginning with a specified address. 
  1898. Now, when writing an integer, instead of using <br>
  1899. <font size=2><br></font><font size=11><pre>
  1900. fprintf(fPtr, "%d", number);<p>
  1901. </pre></font>
  1902.  
  1903. </page>
  1904. <page>
  1905. which could print as few as 1 digit or as many as 11 
  1906. digits (10 digits plus a sign, each of which requires 1 
  1907. byte of storage) for a 4-byte integer, we can use<br>
  1908. <font size=2><br></font><font size=11><pre>
  1909. fwrite(&number, sizeof(int), 1, fPtr);<p>
  1910. </pre></font>
  1911. which always writes 4 bytes (or 2 bytes on a system 
  1912. with 2-byte integers) from variable <b>number</b> to the file 
  1913. represented by <b>fPtr</b> (we will explain the <b>1</b> argument 
  1914. shortly). Later, <b>fread</b> can be used to read 4 of those 
  1915. bytes into integer variable <b>number</b>. Although <b>fread</b> 
  1916. and <b>fwrite</b> read and write data such as integers in fixed-
  1917. size rather than variable-size format, the data they 
  1918. handle is processed in computer "raw data" format (i.e., <br>
  1919.  
  1920. </page>
  1921. <page>
  1922. bytes of data) rather than in <b>printf</b>'s and <b>scanf</b>'s 
  1923. human-readable format. <br>
  1924. <spacer width=16 height=1>The <b>fwrite</b> and <b>fread</b> functions are capable of reading 
  1925. and writing arrays of data to and from disk. The third 
  1926. argument of both <b>fread</b> and <b>fwrite</b> is the number of 
  1927. elements in the array that should be read from disk or 
  1928. written to disk. The preceding <b>fwrite</b> function call 
  1929. writes a single integer to disk, so the third argument is <b>1</b> 
  1930. (as if one element of an array is being written).<br>
  1931. <spacer width=16 height=1>File processing programs rarely write a single field to a 
  1932. file. Normally, they write one <b>struct</b> at a time, as we 
  1933. show in the following examples. <br>
  1934. <spacer width=16 height=1>Consider the following problem statement:<br>
  1935.  
  1936. </page>
  1937. <page>
  1938. <i>Create a credit processing system capable of storing up 
  1939. to 100 fixed-length records. Each record should consist 
  1940. of an account number that will be used as the record 
  1941. key, a last name, a first name, and a balance. The 
  1942. resulting program should be able to update an account, 
  1943. insert a new account record, delete an account, and list 
  1944. all the account records in a formatted text file for 
  1945. printing. Use a randomly accessed file.
  1946. </i><br>
  1947. <spacer width=16 height=1>The next several sections introduce the techniques 
  1948. necessary to create the credit processing program. The 
  1949. program of <a href="^Code::c:s0p3"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.11</b></a> shows how to open a randomly 
  1950. accessed file, define a record format using a <b>struct</b>, 
  1951. write data to the disk, and close the file. This program <br>
  1952.  
  1953. </page>
  1954. <page>
  1955. initializes all 100 records of the file <b>"credit.dat"</b> with 
  1956. empty <b>struct</b>s using function <b>fwrite</b>. Each empty <b>struct</b> 
  1957. contains <b>0</b> for the account number, <b>NULL</b> (represented 
  1958. by empty quotation marks) for the last name, <b>NULL</b> for 
  1959. the first name, and <b>0.0</b> for the balance. The file is 
  1960. initialized in this manner to create space on the disk in 
  1961. which the file will be stored, and to make it possible to 
  1962. determine if a record contains data.<br>
  1963. <spacer width=16 height=1>Function <b>fwrite</b> writes a block (specific number of 
  1964. bytes) of data to a file. In our program, the statement<br>
  1965. <font size=2><br></font><font size=11><pre>
  1966. fwrite(&blankClient, sizeof(struct clientData),<p>
  1967.      1, cfPtr);<p>
  1968. </pre></font>
  1969.  
  1970. </page>
  1971. <page>
  1972. causes the structure <b>blankClient</b> of size <b>sizeof(struct</b> 
  1973. <b>clientData)</b> to be written to the file pointed to by <b>cfPtr</b>. 
  1974. The operator <b>sizeof</b> returns the size in bytes of the 
  1975. object contained in  <a href="^Perform::c:s0p1"><img src="bckgrnds/icons/perf_ico.gif" align=sidebar></a>parentheses (in this case <b>struct</b> 
  1976. <b>clientData</b>). The <b>sizeof</b> operator is a compile-time 
  1977. unary operator that returns an unsigned integer. The 
  1978. <b>sizeof</b> operator can be used to determine the size in 
  1979. bytes of any data type or expression. For example, 
  1980. <b>sizeof(int)</b> is used to determine whether an integer is 
  1981. stored in 2 or 4 bytes on a particular computer. <br>
  1982. <spacer width=16 height=1>Function <b>fwrite</b> can actually be used to write several 
  1983. elements of an array of objects. To write several array 
  1984. elements, the programmer supplies a pointer to an array <br>
  1985.  
  1986. </page>
  1987. <page>
  1988. as the first argument in the call to <b>fwrite</b>, and specifies 
  1989. the number of elements to be written as the third 
  1990. argument in the call to <b>fwrite</b>. In the preceding 
  1991. statement, <b>fwrite</b> was used to write a single object that 
  1992. was not an array element. Writing a single object is 
  1993. equivalent to writing one element of an array, hence the 
  1994. <b>1</b> in the <b>fwrite</b> call.<br>
  1995.  
  1996. </page>
  1997. </section>
  1998. <section type=Body name=Default title="23.8 Writing Data Randomly to a Randomly Accessed File">
  1999. <page>
  2000. <font size=18 bold>23.8 Writing Data Randomly to a Randomly 
  2001. Accessed File</font><hr>
  2002. The program of <a href="^Code::c:s0p4"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.12</b></a> writes data to the file 
  2003. <b>"credit.dat"</b>. It uses the combination of <b>fseek</b> and 
  2004. <b>fwrite</b> to store data at specific locations in the file. 
  2005. Function <b>fseek</b> sets the file position pointer to a specific 
  2006. position in the file, then <b>fwrite</b> writes the data. <br>
  2007. <spacer width=16 height=1>The statement<br>
  2008. <font size=2><br></font><font size=11><pre>
  2009. fseek(cfPtr, (accountNum - 1) <p>
  2010.    * sizeof(struct clientData), SEEK_SET);<p>
  2011. </pre></font>
  2012. positions the file position pointer for the file referenced 
  2013. by <b>cfPtr</b> to the byte location calculated by <br>
  2014.  
  2015. </page>
  2016. <page>
  2017. <b>(accountNum</b> <b>-</b> <b>1)</b> <b>*</b> <b>sizeof(struct</b> <b>clientData)</b>; the 
  2018. value of this expression is called the <i>offset</i> or the 
  2019. <i>displacement</i>. Because the account number is between 
  2020. 1 and 100 but the byte positions in the file start with <b>0</b>, 1 
  2021. is subtracted from the account number when calculating 
  2022. the byte location of the record. Thus, for record 1, the 
  2023. file position pointer is set to byte 0 of the file. The 
  2024. symbolic constant <b>SEEK_SET</b> indicates that the file 
  2025. position pointer is positioned relative to the beginning 
  2026. of the file by the amount of the offset. As the above 
  2027. statement indicates, a seek for account number 1 in the 
  2028. file sets the file position pointer to the beginning of the 
  2029. file because the byte location calculated is 0. <a href="^Illustration::c:s0p8"><img src="bckgrnds/icons/ill_ico.gif" align=sidebar><b>Figure 23.14</b></a> <br>
  2030.  
  2031. </page>
  2032. <page>
  2033. illustrates the file pointer referring to a <b>FILE</b> structure 
  2034. in memory. The file position pointer indicates that the 
  2035. next byte to be read or written is 5 bytes from the 
  2036. beginning of the file.<br>
  2037. <spacer width=16 height=1>The ANSI standard shows the function prototype for 
  2038. <b>fseek</b> as<br>
  2039. <font size=2><br></font><font size=11><pre>
  2040. int fseek(FILE *stream, long int offset, int whence);<p>
  2041. </pre></font>
  2042. where <b>offset</b> is the number of bytes from location 
  2043. <b>whence</b> in the file pointed to by <b>stream</b>. The argument 
  2044. <b>whence</b> can have one of three values--<b>SEEK_SET</b>, 
  2045. <b>SEEK_CUR</b> or <b>SEEK_END</b>--indicating the location 
  2046. in the file from which the seek begins. <b>SEEK_SET</b> <br>
  2047.  
  2048. </page>
  2049. <page>
  2050. indicates that the seek starts at the beginning of the file; 
  2051. <b>SEEK_CUR</b> indicates that the seek starts at the current 
  2052. location in the file; and <b>SEEK_END</b> indicates that the 
  2053. seek starts at the end of the file. These three symbolic 
  2054. constants are defined in the <b>stdio.h</b> header file.<br>
  2055.  
  2056. </page>
  2057. </section>
  2058. <section type=Body name=Default title="23.9 Reading Data Randomly from a Randomly Accessed File">
  2059. <page>
  2060. <font size=18 bold>23.9 Reading Data Randomly from a Randomly Accessed File</font><hr>
  2061. Function <b>fread</b> reads a specified number of bytes from 
  2062. a file into memory. For example, the statement<br>
  2063. <font size=2><br></font><font size=11><pre>
  2064. fread(&client, sizeof(struct clientData), 1, cfPtr);<p>
  2065. </pre></font>
  2066. reads the number of bytes determined by <b>sizeof(struct</b> 
  2067. <b>clientData)</b> from the file referenced by <b>cfPtr</b> and stores 
  2068. the data in the structure <b>client</b>. The bytes are read from 
  2069. the location in the file specified by the file position 
  2070. pointer. Function <b>fread</b> can be used to read several 
  2071. fixed-size array elements by providing a pointer to the <br>
  2072.  
  2073. </page>
  2074. <page>
  2075. array in which the elements will be stored, and by 
  2076. indicating the number of elements to be read. The 
  2077. preceding statement specifies that one element should 
  2078. be read. To read more than one element, specify the 
  2079. number of elements in the third argument of the <b>fread</b> 
  2080. statement. <br>
  2081. <spacer width=16 height=1>The program of <a href="^Code::c:s0p5"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.15</b></a> reads sequentially every record 
  2082. in the <b>"credit.dat"</b> file, determines whether each 
  2083. record contains data, and prints the formatted data for 
  2084. records containing data. The <b>feof</b> function determines 
  2085. when the end of the file is reached, and the <b>fread</b> 
  2086. function transfers data from the disk to the <b>clientData</b> 
  2087. structure <b>client</b>. <br>
  2088.  
  2089. </page>
  2090. </section>
  2091. <section type=Body name=Default title="23.10 Case Study: A Transaction Processing Program">
  2092. <page>
  2093. <font size=18 bold>23.10 Case Study: A Transaction<p>
  2094.  Processing Program</font><hr>
  2095. We now present a substantial transaction processing 
  2096. program using randomly accessed files. The program 
  2097. maintains a bank's account information. The program 
  2098. updates existing accounts, adds new accounts, deletes 
  2099. accounts, and stores a listing of all the current accounts 
  2100. in a text file for printing. We assume that the program 
  2101. of <a href="^Code::c:s0p3"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.11</b></a> has been executed to create the file 
  2102. <b>credit.dat</b>.<br>
  2103. <spacer width=16 height=1>The program has five options. Option 1 calls function 
  2104. <b>textFile</b> to store a formatted list of all the accounts in a <br>
  2105.  
  2106. </page>
  2107. <page>
  2108. text file called <b>accounts.txt</b> that may be printed later. 
  2109. The function uses <b>fread</b> and the sequential file access 
  2110. techniques used in the program of Fig. 11.15. After 
  2111. choosing option 1 the file <b>accounts.txt</b> contains:<br>
  2112. <font size=2><br></font><font size=11><pre>
  2113. Acct  Last Name       First Name    Balance<p>
  2114. 29    Brown           Nancy          -24.54<p>
  2115. 33    Dunn            Stacey         314.33<p>
  2116. 37    Barker          Doug             0.00<p>
  2117. 88    Smith           Dave           258.34<p>
  2118. 96    Stone           Sam             34.98<p>
  2119. <p>
  2120. </pre></font>
  2121. Option 2 calls the function <b>updateRecord</b> to update an 
  2122. account. The function will only update a record that 
  2123. already exists, so the function first checks to see if the <br>
  2124.  
  2125. </page>
  2126. <page>
  2127. record specified by the user is empty. The record is read 
  2128. into structure <b>client</b> with <b>fread</b>, then member <b>acctNum</b> 
  2129. is compared to 0. If it is 0, the record contains no 
  2130. information, and a message is printed stating that the 
  2131. record is empty. Then, the menu choices are displayed. 
  2132. If the record contains information, function 
  2133. <b>updateRecord</b> inputs the transaction amount, 
  2134. calculates the new balance, and rewrites the record to 
  2135. the file. A typical output for option 2 is:<br>
  2136. <font size=2><br></font><font size=11><pre>
  2137. <p>
  2138. Enter account to update (1 - 100): 37<p>
  2139. 37    Barker          Doug             0.00<p>
  2140. <p>
  2141. Enter charge (+) or payment (-): +87.99<p><p>
  2142. </pre></font>
  2143.  
  2144. </page>
  2145. <page>
  2146. <font size=2><br></font><font size=11><pre>
  2147. 37    Barker          Doug            87.99<p>
  2148. <p>
  2149. </pre></font>
  2150. Option 3 calls the function <b>newRecord</b> to add a new 
  2151. account to the file. If the user enters an account number 
  2152. for an existing account, <b>newRecord</b> displays an error 
  2153. message that the record already contains information, 
  2154. and the menu choices are printed again. This function 
  2155. uses the same process to add a new account as does the 
  2156. program in <a href="^Code::c:s0p4"><img src="bckgrnds/icons/code_ico.gif" align=sidebar><b>Fig. 23.12</b></a>. A typical output for option 3 is<br>
  2157. <font size=2><br></font><font size=11><pre>
  2158. <p>
  2159. Enter new account number (1 - 100): 22<p>
  2160. Enter lastname, firstname, balance<p>
  2161. ? Johnston Sarah 247.45<p>
  2162. <p>
  2163. </pre></font>
  2164.  
  2165. </page>
  2166. <page>
  2167. Option 4 calls function <b>deleteRecord</b> to delete a record 
  2168. from the file. Deletion is accomplished by asking the 
  2169. user for the account number and reinitializing the 
  2170. record. If the account contains no information, 
  2171. <b>deleteRecord</b> displays an error message that the 
  2172. account does not exist. Option 5 terminates program 
  2173. execution. The program is shown in <b><a href="^Code::c:s0p6">F<img src="bckgrnds/icons/code_ico.gif" align=sidebar>ig. 23.16</a></b>. Note that 
  2174. the file <b>"credit.dat"</b> is opened for update (reading and 
  2175. writing) using <b>"r+"</b> mode.<br>
  2176.  
  2177. </page>
  2178. </section>
  2179. <section type=Body name=Default title="23.11 Summary">
  2180. <page>
  2181. <font size=18 bold>23.11 Summary</font><hr>
  2182. <indent width=8 delay>*   All data items processed by a computer are reduced 
  2183. to combinations of zeros and ones.  </indent>
  2184. <indent width=8 delay>*   The smallest data item in a computer can assume the 
  2185. value <b>0</b> or the value <b>1</b>. Such a data item is called a bit 
  2186. (short for "binary digit"--a digit that can assume one of 
  2187. two values). </indent>
  2188. <indent width=8 delay>*  Digits, letters, and special symbols are referred to as 
  2189. characters. The set of all characters that may be used to 
  2190. write programs and represent data items on a particular 
  2191. computer is called that computer's character set. Every 
  2192. character in the computer's character set is represented </indent>
  2193.  
  2194. </page>
  2195. <page>
  2196. <indent width=8 delay>*   as a pattern of eight <b>1</b>s and <b>0</b>s (called a byte). </indent>
  2197. <indent width=8 delay>*   A field is a group of characters that conveys meaning. </indent>
  2198. <indent width=8 delay>*   A record is a group of related fields. </indent>
  2199. <indent width=8 delay>*   At least one field in each record is normally chosen 
  2200. as a record key. The record key identifies a record as 
  2201. belonging to a particular person or entity. </indent>
  2202. <indent width=8 delay>*   The most popular type of organization for records in 
  2203. a file is called a sequential access file in which records 
  2204. are accessed consecutively until the desired data are 
  2205. located. </indent>
  2206. <indent width=8 delay>*  A group of related files is sometimes called a database. A collection of programs designed to create and </indent>
  2207.  
  2208. </page>
  2209. <page>
  2210. <indent width=8 delay>*   manage databases is called a database management system (DBMS).</indent>
  2211. <indent width=8 delay>*   C views each file simply as a sequential stream of 
  2212. bytes.</indent>
  2213. <indent width=8 delay>*   C automatically opens three files and their associated 
  2214. streams--standard input, standard output, and standard 
  2215. error--when program execution begins.</indent>
  2216. <indent width=8 delay>*   The file pointers assigned to the standard input, standard output, and standard error are <b>stdin</b>, <b>stdout</b>, and 
  2217. <b>stderr</b>, respectively.</indent>
  2218. <indent width=8 delay>*   Function <b>fgetc</b> reads a character from a specified file. </indent>
  2219. <indent width=8 delay>*   Function <b>fputc</b> writes a character to a specified file. </indent>
  2220. <indent width=8 delay>*   Function <b>fgets</b> reads a line from a specified file.</indent>
  2221.  
  2222. </page>
  2223. <page>
  2224. <indent width=8 delay>*   Function <b>fputs</b> writes a line to a specified file.</indent>
  2225. <indent width=8 delay>*   <b>FILE</b> is a structure type defined in the <b>stdio.h</b> header 
  2226. file. The programmer need not know the specifics of 
  2227. this structure to use files. As a file is opened, a pointer 
  2228. to the file's <b>FILE</b> structure is returned. </indent>
  2229. <indent width=8 delay>*   Function <b>fopen</b> takes two arguments--a file name 
  2230. and a file open mode--and opens the file. If the file 
  2231. exists, the contents of the file are discarded without 
  2232. warning. If the file does not exist and the file is being 
  2233. opened for writing, <b>fopen</b> creates the file. </indent>
  2234. <indent width=8 delay>*   Function <b>feof</b> determines whether the end-of-file 
  2235. indicator for a file has been set.  </indent>
  2236. <indent width=8 delay>*  Function <b>fprintf</b> is equivalent to <b>printf</b> except </indent>
  2237.  
  2238. </page>
  2239. <page>
  2240. <indent width=8 delay>*   <b>fprintf</b> receives as an argument a pointer to the file to 
  2241. which the data will be written. </indent>
  2242. <indent width=8 delay>*   Function <b>fclose</b> closes the file pointed to by its argument.</indent>
  2243. <indent width=8 delay>*  To create a file, or to discard the contents of a file 
  2244. before writing data, open the file for writing (<b>"w"</b>). To 
  2245. read an existing file, open it for reading (<b>"r"</b>). To add 
  2246. records to the end of an existing file, open the file for 
  2247. appending (<b>"a"</b>). To open a file so that it may be written to and read from, open the file for updating in one of 
  2248. the three updating modes--<b>"r+"</b>, <b>"w+"</b>, or <b>"a+"</b>. 
  2249. Mode <b>"r+"</b> simply opens the file for reading and writing. Mode <b>"w+"</b> creates the file if it does not exist, and </indent>
  2250.  
  2251. </page>
  2252. <page>
  2253. <indent width=8 delay>*   discards the current contents of the file if it does exist. 
  2254. Mode <b>"a+"</b> creates the file if it does not exist, and writing is done at the end of the file.  </indent>
  2255. <indent width=8 delay>*   Function <b>fscanf</b> is equivalent to <b>scanf</b> except <b>fscanf</b> 
  2256. receives as an argument a pointer to the file (normally 
  2257. other than <b>stdin</b>) from which the data will be read. </indent>
  2258. <indent width=8 delay>*   Function <b>rewind</b> causes the program to reposition 
  2259. the file position pointer for the specified file to the 
  2260. beginning of the file.</indent>
  2261. <indent width=8 delay>*   Random access file processing is used to access a 
  2262. record directly. </indent>
  2263. <indent width=8 delay>*  To facilitate random access, data is stored in fixed-
  2264. length records. Since every record is the same length, </indent>
  2265.  
  2266. </page>
  2267. <page>
  2268. <indent width=8 delay>*   the computer can quickly calculate (as a function of the 
  2269. record key) the exact location of a record in relation to 
  2270. the beginning of the file.</indent>
  2271. <indent width=8 delay>*   Data can be added easily to a random access file 
  2272. without destroying other data in the file. Data stored 
  2273. previously in a file with fixed-length records can also 
  2274. be changed and deleted without rewriting the entire file.</indent>
  2275. <indent width=8 delay>*   Function <b>fwrite</b> writes a block (specific number of 
  2276. bytes) of data to a file. </indent>
  2277. <indent width=8 delay>*   The compile-time operator <b>sizeof</b> returns the size in 
  2278. bytes of its operand.</indent>
  2279. <indent width=8 delay>*  Function <b>fseek</b> sets the file position pointer to a specific position in a file based on the starting location of </indent>
  2280.  
  2281. </page>
  2282. <page>
  2283. <indent width=8 delay>*   the seek in the file. The seek can start from one of three 
  2284. locations--<b>SEEK_SET</b> starts from the beginning of 
  2285. the file, <b>SEEK_CUR</b> starts from the current position in 
  2286. the file, and <b>SEEK_END</b> starts from the end of the file.</indent>
  2287. <indent width=8 delay>*   Function <b>fread</b> reads a block (specific number of 
  2288. bytes) of data from a file. </indent>
  2289. <br>
  2290.  
  2291. </page>
  2292. </section>
  2293.  
  2294. <section type=Popup name=Debug title="Testing">
  2295. <page>
  2296. This chapter does not contain any Testing and Debugging tips.
  2297. </page>
  2298. </section>
  2299. <section type=Popup name=AppletPopup title="Applet Examples">
  2300. <page>
  2301. This chapter does not contain any Applet Examples.
  2302. </page>
  2303. </section>
  2304. <section type=Popup name=Engineer title="Engineering">
  2305. <page>
  2306. This chapter does not contain any Software Engineering Observations.
  2307. </page>
  2308. </section>
  2309. </chapter>
  2310. </html>
  2311. </html>
  2312.